Examining the Excel-like Filtering example, how would you set/remove filtering with javascript?

1 Answer 43 Views
Filter Grid
Lawrence
Top achievements
Rank 1
Lawrence asked on 17 Oct 2023, 01:23 PM

In the Excel-like Filtering example for ASP.NET AJAX, the RadGrid utilizes filtering by way of a HeaderContextFilterMenu.  Because of this distinction, the coding samples for setting/removing filters via javascript seem to be incompatible.

For example, with a standard RadGrid you could set a filter with the following javascript:

var masterTable = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
masterTable.filter("OrderID", 10254, Telerik.Web.UI.GridFilterFunction.GreaterThan, true);

OR

var masterTable = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
masterTable.filter("AccessLevel", "User", "EqualTo");
masterTable.sort("Name");

 

But since I'm using the "Excel-like Filtering" mode/style, when I try this same logic, it returns the following error after calling getElementByClassName:

Uncaught TypeError: d is null

 

My assumption is that there is a different set of steps/calls needed to set filtering when HeaderContextFilterMenu is involved.  Any ideas?

 

DefaultCS.aspx:

<%@ Page Language="c#" AutoEventWireup="false" CodeFile="DefaultCS.aspx.cs" Inherits="Telerik.GridExamplesCSharp.Functionality.Filtering.ExcelLikeFiltering.DefaultCS" %>
 
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head runat="server">
    <title>Telerik ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <telerik:RadScriptManager runat="server" ID="RadScriptManager1" />
    <telerik:RadSkinManager ID="RadSkinManager1" runat="server" ShowChooser="true" />
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" EnableAJAX="true">
     <div class="demo-container no-bg">
            <telerik:RadGrid RenderMode="Lightweight" ID="RadGrid1" AllowFilteringByColumn="true" runat="server" FilterType="HeaderContext" EnableHeaderContextMenu="true" 
                EnableHeaderContextFilterMenu="true" AllowPaging="True" PagerStyle-AlwaysVisible="true" OnFilterCheckListItemsRequested="RadGrid1_FilterCheckListItemsRequested" DataSourceID="SqlDataSource1" AllowSorting="true" GroupingEnabled="true">
                <MasterTableView DataSourceID="SqlDataSource1" AutoGenerateColumns="False" DataKeyNames="CustomerID">
                    <Columns>
                        <telerik:GridBoundColumn FilterCheckListEnableLoadOnDemand="true" DataField="ContactName" FilterControlAltText="Filter ContactName column" HeaderText="ContactName" SortExpression="ContactName" UniqueName="ContactName" AutoPostBackOnFilter="true" CurrentFilterFunction="StartsWith">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn FilterCheckListEnableLoadOnDemand="true" DataField="ContactTitle" FilterControlAltText="Filter ContactTitle column" HeaderText="ContactTitle" SortExpression="ContactTitle" UniqueName="ContactTitle">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Address" FilterControlAltText="Filter Address column" HeaderText="Address" SortExpression="Address" UniqueName="Address">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn FilterCheckListEnableLoadOnDemand="true" DataField="City" FilterControlAltText="Filter City column" HeaderText="City" SortExpression="City" UniqueName="City">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn FilterCheckListEnableLoadOnDemand="true" DataField="Country" FilterControlAltText="Filter Country column" HeaderText="Country" SortExpression="Country" UniqueName="Country">
                        </telerik:GridBoundColumn>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>
        </telerik:RadAjaxPanel>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT * FROM [Customers]"></asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

 

DefaultCS.aspx.cs:

using Telerik.Web.UI;
using System;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
 
namespace Telerik.GridExamplesCSharp.Functionality.Filtering.ExcelLikeFiltering
{
    public partial class DefaultCS : System.Web.UI.Page
    {
        protected void RadGrid1_FilterCheckListItemsRequested(object sender, GridFilterCheckListItemsRequestedEventArgs e)
        {
            string DataField = (e.Column as IGridDataColumn).GetActiveDataField();
 
            e.ListBox.DataSource = GetDataTable(DataField);
            e.ListBox.DataKeyField = DataField;
            e.ListBox.DataTextField = DataField;
            e.ListBox.DataValueField = DataField;
            e.ListBox.DataBind();
        }
 
        public DataTable GetDataTable(string field)
        {
            string query = string.Format("SELECT DISTINCT {0} FROM Customers", field);
 
            String ConnString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(ConnString);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = new SqlCommand(query, conn);
 
            DataTable myDataTable = new DataTable();
 
            conn.Open();
            try
            {
                adapter.Fill(myDataTable);
            }
            finally
            {
                conn.Close();
            }
 
            return myDataTable;
        }
    }
}

1 Answer, 1 is accepted

Sort by
0
Attila Antal
Telerik team
answered on 19 Oct 2023, 10:33 AM

Hi Lawrence,

Currently, the HeaderContextMenu Filter does not expose public JavaScript APIs to apply filtering, but there is a way you can apply filtering programmatically in this case.

For example, you can use the fireCommand() method to trigger a custom command and pass along the values you want to filter by.

function ApplyFilters(sender, args) {
    // Your custom command name                
    var commandName = 'ApplyFilter';

    // Your custom arguments
    // JSON data containing an array of object, each object contains the ColumnName and the Filter values
    var commandArguments = JSON.stringify([
        {
            "ColumnName": "ShipName", // Column name
            "FilterValues": [ // filter values
                "Name 2",
                "Name 4",
                "Name 6"
            ]
        }
    ]);

    // Reference the TableView object
    var tableView = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
    // call the fireCommand() method and pass the command name and arguments to it
    tableView.fireCommand(commandName, commandArguments);
}

In the ItemCommand event of the Grid, you can capture this command. The event arguments contain the CommandName (ColumnName) and CommandArguments (Filter values). Since the CommandArguments is a JSON string, you can use a JavaScriptSerializer to deserialize it to an object and use the values to fire the HeaderContextFilterMenu command for the Grid. See How to Fire Command Events for more details.

rotected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
    RadGrid grid = (RadGrid) sender;

    GridHeaderItem headerItem = grid.MasterTableView.GetItems(GridItemType.Header).FirstOrDefault() as GridHeaderItem;

    if (e.CommandName == "ApplyFilter")
    {
        AdvancedJavaScriptSerializer serializer = new AdvancedJavaScriptSerializer();

        List<FilterData> filters = serializer.Deserialize<List<FilterData>>(e.CommandArgument.ToString());

        foreach (FilterData filter in filters)
        {
            GridColumn gridColumn = grid.MasterTableView.GetColumn(filter.ColumnName);

            gridColumn.ListOfFilterValues = filter.FilterValues.ToArray();
        }

        headerItem.FireCommandEvent("HeaderContextMenuFilter", new Triplet()
        {
            First = filters[0].ColumnName,
            Second = new Pair()
            {
                First = "NoFilter",
                Second = string.Empty
            },
            Third = new Pair()
            {
                First = "NoFilter",
                Second = string.Empty
            }
        });
    }
}

public class FilterData
{
    public string ColumnName { get; set; }
    public List<string> FilterValues { get; set; }
}

Note: you can apply filtering on multiple columns at once if the JSON data contains multiple objects.

Example

var commandArguments = JSON.stringify([
    {
        "ColumnName": "ShipName", // Column name
        "FilterValues": [ // filter values
            "Name 2",
            "Name 4",
            "Name 6"
        ]
    },
    {
        "ColumnName": "ShipCountry", // Column name
        "FilterValues": [ // filter values
            "Country 7",
            "Country 11"
        ]
    }
]);

 

Clearing the filter would be a little bit easier and quicker to implement. Access the respective Column by its unique name, and call the _clearFilterButtonClickHandler() internal method.

function ClearFilters(sender, args) {
    var tableView = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
    var shipNameColumn = tableView.getColumnByUniqueName('ShipName');
    shipNameColumn._clearFilterButtonClickHandler(args.get_domEvent());
}

I hope this will prove helpful.

Regards,
Attila Antal
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Telerik family, check out our getting started resources
Tags
Filter Grid
Asked by
Lawrence
Top achievements
Rank 1
Answers by
Attila Antal
Telerik team
Share this question
or