This is a migrated thread and some comments may be shown as answers.

RadGrid enable filter code behind

11 Answers 1917 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Suzy
Top achievements
Rank 2
Suzy asked on 16 Apr 2015, 10:00 AM

Hi,

I have a radgrid with filter on field set on.  I need to be able to set the filter of a specific field to a fixed value and enable the filter field.  But this is user dependant.

How can I accomplish this?

My radgrid :

<telerik:RadGrid ID="grdCodes" GridLines="None" runat="server" PageSize="20" AllowPaging="True" AutoGenerateColumns="False" AllowFilteringByColumn="true"
           OnInsertCommand="grdCodes_InsertCommand" OnUpdateCommand="grdCodes_UpdateCommand"
           OnNeedDataSource="grdCodes_NeedDataSource" OnItemDataBound="grdCodes_ItemDataBound" OnItemCreated="grdCodes_ItemCreated" OnPreRender="grdCodes_PreRender" >
           <MasterTableView CommandItemDisplay="Top" HorizontalAlign="NotSet" EditMode="InPlace" AutoGenerateColumns="False">
               <Columns>
                   <telerik:GridEditCommandColumn UniqueName="EditColumn" ButtonType="ImageButton" ItemStyle-Width="10px" />
 
                   <telerik:GridTemplateColumn HeaderText="System" ItemStyle-Width="20%" SortExpression="system" UniqueName="system" DataField="system">
                       <FilterTemplate>
                           <telerik:RadComboBox ID="ddlSystemFilter" runat="server" OnClientSelectedIndexChanged="FilterSystemIndexChanged" AppendDataBoundItems="true" SelectedValue='<%# ((GridItem)Container).OwnerTableView.GetColumn("system").CurrentFilterValue %>'>
                               <Items>
                                   <telerik:RadComboBoxItem Text="All" />
                               </Items>
                           </telerik:RadComboBox>
                           <telerik:RadScriptBlock ID="RadScriptBlock2" runat="server">
                               <script type="text/javascript">
                                   function FilterSystemIndexChanged(sender, args) {
                                       var tableView = $find("<%# ((GridItem)Container).OwnerTableView.ClientID %>");
                                       tableView.filter("system", args.get_item().get_value(), "EqualTo");
                                   }
                               </script>
                           </telerik:RadScriptBlock>
                       </FilterTemplate>
                       <ItemTemplate>
                           <%# CartaMundi.BusinessLogic.Codes.GetDescription(cmWeb.Classes.Constants.SYSTEM_GENERAL,"SYSTEM", DataBinder.Eval(Container.DataItem, "system")) %>
                       </ItemTemplate>
                       <EditItemTemplate>
                           <telerik:RadComboBox runat="server" ID="ddlSystem" ></telerik:RadComboBox>
                       </EditItemTemplate>
                   </telerik:GridTemplateColumn>
                   <telerik:GridBoundColumn DataField="field_name" HeaderStyle-Width="20%" HeaderText="Field name" SortExpression="field_name" UniqueName="field_name" ShowFilterIcon="false" CurrentFilterFunction="Contains" AutoPostBackOnFilter="true">
                       <ColumnValidationSettings EnableRequiredFieldValidation="true">
                           <RequiredFieldValidator Text="<img src='/CMIT/Images/Warning.gif' border='0'>" Display="Dynamic" ToolTip="Field name is required." ErrorMessage="-Field name is required." ></RequiredFieldValidator>
                       </ColumnValidationSettings>
                   </telerik:GridBoundColumn>
                   <telerik:GridBoundColumn DataField="field_value" HeaderStyle-Width="20%" HeaderText="Field value" SortExpression="field_value" UniqueName="field_value" ShowFilterIcon="false" CurrentFilterFunction="Contains" AutoPostBackOnFilter="true">
                       <ColumnValidationSettings EnableRequiredFieldValidation="true">
                           <RequiredFieldValidator Text="<img src='/CMIT/Images/Warning.gif' border='0'>" Display="Dynamic" ToolTip="Field value is required." ErrorMessage="-Field value is required." ></RequiredFieldValidator>
                       </ColumnValidationSettings>
                   </telerik:GridBoundColumn>
                   <telerik:GridBoundColumn DataField="description" HeaderStyle-Width="40%" HeaderText="Description" SortExpression="description" UniqueName="description" ShowFilterIcon="false" CurrentFilterFunction="Contains" AutoPostBackOnFilter="true" >
                       <ColumnValidationSettings EnableRequiredFieldValidation="true">
                           <RequiredFieldValidator Text="<img src='/CMIT/Images/Warning.gif' border='0'>" Display="Dynamic" ToolTip="Description is required." ErrorMessage="-Description is required." ></RequiredFieldValidator>
                       </ColumnValidationSettings>
                   </telerik:GridBoundColumn>
               </Columns>
           </MasterTableView>
           <ClientSettings AllowKeyboardNavigation="true"></ClientSettings>
       </telerik:RadGrid>

The fields that can have fixed values is the GridTemplateColumn 'System' and the GridBoundColumn 'field_value'

I was able to set the default value but there is was no option to set the field enabled.

protected void grdCodes_PreRender(object sender, EventArgs e)
{
     
        if (BLogic.UserRights.Authorised(CurrentUser, "ProjectGroups", "*DSP", Classes.Constants.SYSTEM_DESIGN ))
        {
            grdCodes.MasterTableView.FilterExpression = "(Convert.ToString(it[\"system\"]) = \"" + cmWeb.Classes.Constants.SYSTEM_DESIGN + "\") AND (it[\"field_name\"].ToString().Contains(\"PRJGROUPS\"))";
            GridColumn column = grdCodes.MasterTableView.GetColumnSafe("system");
            column.CurrentFilterFunction = GridKnownFunction.EqualTo;
            column.CurrentFilterValue = cmWeb.Classes.Constants.SYSTEM_DESIGN;
            column = grdCodes.MasterTableView.GetColumnSafe("field_name");
            column.CurrentFilterFunction = GridKnownFunction.EqualTo;
            column.CurrentFilterValue = "PRJGROUPS";
                                 
            grdCodes.MasterTableView.Rebind();
 
        }
}
 

There are users that may not be able to select other values in the filter and have a fixed value.  Other user must be are able to use the filter as they wish.

The part of the code '(BLogic.UserRights.Authorised(CurrentUser, "ProjectGroups", "*DSP", Classes.Constants.SYSTEM_DESIGN ))' decides if the users has limitid selection options.

Can this be done?

Kind regards

Suzy

 

 

11 Answers, 1 is accepted

Sort by
0
Eyup
Telerik team
answered on 21 Apr 2015, 08:52 AM
Hi Suzy,

Please note that modifying the FilterExpression is quite tricky and it can be error-prone, therefore, it is not recommended.

Instead, you can use the filter method:
https://docs.telerik.com/devtools/aspnet-ajax/controls/grid/client-side-programming/gridtableview-object/methods/filter

You can examine an actual implementation in the following live sample:
http://demos.telerik.com/aspnet-ajax/grid/examples/functionality/filtering/filter-templates/defaultcs.aspx

Alternatively, you can use the FireCommandEvent method to achieve the requested functionality on the code-behind:
http://www.telerik.com/help/aspnet-ajax/grid-fire-command-event-from-code.html


For example, in case you want to apply an initial filter, you can use the following approach:
protected void RadGrid1_PreRender(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridFilteringItem filterItem = RadGrid1.MasterTableView.GetItems(
             GridItemType.FilteringItem)[0] as GridFilteringItem;
  
        GridColumn col = RadGrid1.MasterTableView.GetColumn("ShipName");
        col.CurrentFilterValue = "Success";
        filterItem.FireCommandEvent("Filter", new Pair("StartsWith", "ShipName"));
    }
}

In addition you can also set the AllowFiltering property of the column to false if the user would not be allowed to filter.

Hope this helps.


Regards,
Eyup
Telerik
 

See What's Next in App Development. Register for TelerikNEXT.

 
0
Suzy
Top achievements
Rank 2
answered on 21 Apr 2015, 09:19 AM

Hi Eyup,

It's the last sentence that I'm not able to do :

In addition you can also set the AllowFiltering property of the column to false if the user would not be allowed to filter.

There is no AllowFiltering for the GridColumn.

Can you please give an example of setting the column to AllowFiltering False?

Kind regards

 Suzy

0
Accepted
Eyup
Telerik team
answered on 22 Apr 2015, 06:59 AM
Hi Suzy,

You should cast the column to the specific type, e.g. GridBoundColumn. You can also cast it to IGridDataColumn for a more generic solution.

Please give it a try and let me know how it goes.

Regards,
Eyup
Telerik
 

See What's Next in App Development. Register for TelerikNEXT.

 
0
Suzy
Top achievements
Rank 2
answered on 23 Apr 2015, 08:56 AM

Thanks Eyup,

 I used the IGridDataColumn and it works!

Thanks a lot.

Suzy

0
John
Top achievements
Rank 1
answered on 07 Nov 2017, 05:39 PM

Is there a way to filter on 2 columns using the FireCommandEvent?  I want to setup default filtering based upon values entered on a different page.

 

thanks

0
Attila Antal
Telerik team
answered on 10 Nov 2017, 03:10 PM
Hi John,

One possible way would be, to manually change the text inside the filter item's textboxes the column filter functions for as many columns as you want, then use the FireCommand event to apply filtering on one of the columns. All the other columns will be filtered automatically.

For example:
protected void Button1_Click(object sender, EventArgs e)
{
    GridCommandItem commandItem = (sender as Button).NamingContainer as GridCommandItem;
    GridFilteringItem filterItem = commandItem.OwnerTableView.GetItems(GridItemType.FilteringItem)[0] as GridFilteringItem;
     
    // Configure filter options for the desired columns
    ConfigureColumnFilter(filterItem, "Column1", "1");
    ConfigureColumnFilter(filterItem, "Column2", "10");
    ConfigureColumnFilter(filterItem, "Column3", "100");
     
    // Apply filtering on any of the columns
    filterItem.FireCommandEvent("Filter", new Pair("GreaterThanOrEqualTo", "Column1"));
}
 
// Method to change the filtering options
private void ConfigureColumnFilter(GridCommandItem commandItem, GridFilteringItem filterItem, string colName, string value)
{
    GridBoundColumn col = filterItem.OwnerTableView.GetColumn(colName) as GridBoundColumn;
 
    TextBox filterBox = filterItem[colName].Controls[0] as TextBox;
    filterBox.Text = value;
     
    switch (colName)
    {
        case "Column1":
            col.CurrentFilterFunction = GridKnownFunction.GreaterThanOrEqualTo;
            break;
        case "Column2":
            col.CurrentFilterFunction = GridKnownFunction.EqualTo;
            break;
        case "Column3":
            col.CurrentFilterFunction = GridKnownFunction.LessThan;
            break;
    }
}

Attached you can find a working sample of this scenario. Please give it a try and see if that works for you.

Kind Regards,
Attila Antal
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
John
Top achievements
Rank 1
answered on 13 Nov 2017, 01:56 PM

Hi Attila,

Thank you for the information.  I thought I tried this earlier and it didn't work but probably missed something!  I will look at you sample and above code to see where I went wrong. 

thanks again

john

0
John
Top achievements
Rank 1
answered on 15 Nov 2017, 07:00 PM

Attila,

I was not able to get your solution to work.

I am using the following which does fill in the Filter text boxes with the values (I also tried using you code to fill in the textbox , which didn't work).

This is a snippet of my code:

....

Dim filterItem As GridFilteringItem = TryCast(RadGrid1.MasterTableView.GetItems(GridItemType.FilteringItem)(0), GridFilteringItem)
Dim col As GridColumn = Nothing

col = RadGrid1.MasterTableView.GetColumnSafe("AuditType")
col.CurrentFilterValue = "Offsite"

col = RadGrid1.MasterTableView.GetColumnSafe("HasDoc")
col.CurrentFilterValue = "Y"
filterItem.FireCommandEvent("Filter", New Pair("EqualTo", "AuditType"))

 

Now the Filter Textboxes are indeed showing the 2 values that I set above, but the FireCommandEvent only filters on what is passed in and ignores all other filter values.  So other than modifying the FilterExpression manually, is there a way to filter on 2 columns when the grid first loads in code-behind?

 

thanks

 

0
Attila Antal
Telerik team
answered on 17 Nov 2017, 03:47 PM
Hi John,

Please ensure that the CurrentFilterFunction is set for the respective columns when filtering. You could apply different filtering function for different columns or apply the same for all.

Set filter for column
private void ConfigureColumnFilter(GridCommandItem commandItem, GridFilteringItem filterItem, string colName, string value)
{
    GridBoundColumn col = filterItem.OwnerTableView.GetColumn(colName) as GridBoundColumn;
  
    TextBox filterBox = filterItem[colName].Controls[0] as TextBox;
    filterBox.Text = value;
      
    switch (colName)
    {
        case "Column1":
            col.CurrentFilterFunction = GridKnownFunction.GreaterThanOrEqualTo;
            break;
        case "Column2":
            col.CurrentFilterFunction = GridKnownFunction.EqualTo;
            break;
        case "Column3":
            col.CurrentFilterFunction = GridKnownFunction.LessThan;
            break;
    }
}

Clear all filters
protected void ButtonClearFilter_Click(object sender, EventArgs e)
{
    GridCommandItem commandItem = (sender as Button).NamingContainer as GridCommandItem;
    commandItem.OwnerTableView.FilterExpression = string.Empty;
    foreach (GridColumn column in commandItem.OwnerTableView.RenderColumns)
    {
        column.CurrentFilterFunction = GridKnownFunction.NoFilter;
        column.CurrentFilterValue = string.Empty;
    }
    commandItem.OwnerTableView.Rebind();
}

If the issue still persist, please open a formal support ticket, modify the sample attached in my previous reply to reflect the exact scenario and send it back to us for further investigation.

Kind Regards,
Attila Antal
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
John
Top achievements
Rank 1
answered on 20 Nov 2017, 04:02 PM

Attila,

  I was finally able to get it to work!  Thank you for the help.

0
Attila Antal
Telerik team
answered on 15 Aug 2019, 03:15 PM

In case the Excel-Like Filtering is used (FilterType="HeaderContext"), the initial filtering is done as follows. FilterCommand explained in the How to Fire Command Events article.

protected void RadGrid1_PreRender(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridHeaderItem header = RadGrid1.MasterTableView.GetItems(GridItemType.Header)[0] as GridHeaderItem;

        Pair firstCondition = new Pair();
        firstCondition.First = "GreaterThan";
        firstCondition.Second = "5";

        Pair secondCondition = new Pair();
        secondCondition.First = "LessThan";
        secondCondition.Second = "10";

        Triplet commandArguments = new Triplet();
        commandArguments.First = "OrderID";
        commandArguments.Second = firstCondition;
        commandArguments.Third = secondCondition;

        header.FireCommandEvent("HeaderContextMenuFilter", commandArguments);
    }
}

 

Kind regards, Attila Antal
Progress Telerik

Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Tags
Grid
Asked by
Suzy
Top achievements
Rank 2
Answers by
Eyup
Telerik team
Suzy
Top achievements
Rank 2
John
Top achievements
Rank 1
Attila Antal
Telerik team
Share this question
or