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

How does custom filtering work in a RadGrid

1 Answer 154 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Randall
Top achievements
Rank 2
Randall asked on 03 Aug 2010, 08:30 PM

Hello,

I am using RadControls for ASP.NET AJAX 2009.1.527.20 and I have a RadGrid that requires some custom filtering.

For the first custom filter, I want a RadComboBox to drop down with a CheckBoxList.  Each item in the CheckBoxList contains a CheckBox, an Image, and a Description.  Then below that I would like "OK" and "Cancel" buttons.  OK would apply the filter, and Cancel would just close the RadComboBox dropdown and not affect the RadGrid.

For the next custom filter, I have 5 columns of integers.  I want one RadComboBox to drop down with a CheckBoxList.  Each item in the CheckBoxList contains a CheckBox and a Description.  Then below that I would like "OK" and "Cancel" buttons.  OK would apply the filter, and Cancel would just close the RadComboBox dropdown and not affect the RadGrid.

I have (sort of) been able to create the <FilterTemplate> for each of these, but I do not know how to do a few things:

  1. How do I add the "OK" and "Cancel" buttons to the template?

  2. How do I apply the results of the CheckBoxes in the CheckBoxList to the RadGrid filter functionality?

 

I have provided a sample VS 2010 web application that demonstrates what I have and want.  In this sample, I am using an XmlDataSource so I can provide sample data.  In my real application, I am binding the RadGrid using the OnNeedDataSource event.

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RadGridSample.Default" %>
  
<%@ Register Namespace="Telerik.Web.UI" TagPrefix="telerik" Assembly="Telerik.Web.UI" %>
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  
<head id="Head1" runat="server">
  <title>RadGrid Sample - Custom Filtering</title>
</head>
<body>
  <form id="form1" runat="server">
  <telerik:RadScriptManager ID="RadScriptManager1" runat="server" />
  
  <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
    <style type="text/css">
      html
      {
          overflow: hidden;
      }
      html,
      body,
      form
      {
          margin: 0;
          height: 100%;
      }
      .GridWrapper
      {
        height: 100%;
        width: 100%;
      }
      body
      {
        background-color: #F5DEB3;
        color: #660000;
        font-family: Tahoma, Verdana, Arial, Sans-Serif;
        font-size: 8pt;
      }
      .combo-item-template input,
      .combo-item-template label
      {
        vertical-align:middle;
      }
      .combo-item-template img
      {
        vertical-align:top;
      }
      .rcbSlide,
      .RadComboBoxDropDown_Default
      {
        width: 300px !important;
      }
      .StatusGreen
      {
        background: url('../images/1_green_light.gif') no-repeat center;
      }
      .StatusYellow
      {
        background: url('../images/2_yellow_light.gif') no-repeat center;
      }
      .StatusRed
      {
        background: url('../images/3_red_light.gif') no-repeat center;
      }
      .StatusWarning
      {
        background: url('../images/4_warning_light.gif') no-repeat center;
      }
      .StatusPending
      {
        background: url('../images/5_pending_light.gif') no-repeat center;
      }
    </style>
  </telerik:RadCodeBlock>
  
  <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"
      OnAjaxRequest="RadAjaxManager1_AjaxRequest">
    <AjaxSettings>
      <telerik:AjaxSetting AjaxControlID="RadGrid1">
        <UpdatedControls>
            <telerik:AjaxUpdatedControl ControlID="RadGrid1" />
        </UpdatedControls>
      </telerik:AjaxSetting>
    </AjaxSettings>
  </telerik:RadAjaxManager>
  
  <div class="GridWrapper">
  
    <!-- Grid start -->
    <telerik:RadGrid runat="server"
      ID="RadGrid1"
      AllowFilteringByColumn="true"
      AllowPaging="True"
      AllowSorting="True"
      AutoGenerateColumns="False"
      DataSourceID="XmlDataSource1"
      Height="300px"
      OnItemCommand="RadGrid1_ItemCommand"
      OnItemDataBound="RadGrid1_ItemDataBound"
      OnPreRender="RadGrid1_PreRender"
      PageSize="10"
      Width="800px"
      >
  
      <ClientSettings EnableRowHoverStyle="true">
        <Resizing AllowColumnResize="true"
                  ClipCellContentOnResize="true"
                  EnableRealTimeResize="true" />
        <Selecting AllowRowSelect="true" />
        <Scrolling AllowScroll="true" UseStaticHeaders="true" />
      </ClientSettings>
  
      <MasterTableView AllowPaging="true" TableLayout="Fixed">
        <Columns>
          <telerik:GridBoundColumn
            DataField="Status"
            AllowFiltering="true"
            AllowSorting="true"
            FilterControlWidth="42px"
            HeaderText="Status"
            SortExpression="Status"
            UniqueName="Status"
            >
            <HeaderStyle HorizontalAlign="Center" Width="56px" />
            <ItemStyle HorizontalAlign="Center" />
  
            <FilterTemplate>
              <telerik:RadComboBox runat="server"
                ID="RadComboBox1"
                HighlightTemplatedItems="true"
                Width="42"
                >
                <Items>
                  <telerik:RadComboBoxItem Text="" Count="1"
                     Info="All needed updates installed"
                     Image="../images/1_green_light.gif" />
                  <telerik:RadComboBoxItem Text="" Count="2"
                     Info="Some updates pending or unknown"
                     Image="../images/2_yellow_light.gif" />
                  <telerik:RadComboBoxItem Text="" Count="3"
                     Info="Some updates failed"
                     Image="../images/3_red_light.gif" />
                  <telerik:RadComboBoxItem Text="" Count="4"
                     Info="Deregistered or timed out"
                     Image="../images/4_warning_light.gif" />
                  <telerik:RadComboBoxItem Text="" Count="5"
                     Info="Waiting for rollup information"
                     Image="../images/5_pending_light.gif" />
                </Items>
                <ItemTemplate>
                  <div onclick="StopPropagation(event)"
                       class="combo-item-template">
                    <asp:CheckBox runat="server" ID="chk1" Checked="true"
                         onclick="onCheckBoxClick_Status(this)"/>
                    <asp:Label runat="server" ID="Label1"
                         AssociatedControlID="chk1">
                      <span class="NoWrap">
                        <img id="img<%# DataBinder.Eval(Container, "Attributes['Count']") %>"
                            src="<%# DataBinder.Eval(Container, "Attributes['Image']") %>"
                            alt="<%# DataBinder.Eval(Container, "Attributes['Info']") %>" />
                        <%# DataBinder.Eval(Container, "Attributes['Info']")%></span></asp:Label>
                  </div>
                </ItemTemplate>
              </telerik:RadComboBox>
              <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
                <script type="text/javascript" language="javascript">
                  function onCheckBoxClick_Status(chk)
                  {
                    var combo = $find('<%# ((GridItem)Container).FindControl("RadComboBox1").ClientID %>');
                    var text  = "";
                    var values = "";
  
                    // Get the collection of all items.
                    var items = combo.get_items();
  
                    // Enumerate all items.
                    for (var i = 0; i < items.get_count(); i++)
                    {
                      // Get the checkbox element of the current item.
                      var chk1 = $get(combo.get_id() + "_i" + i + "_chk1");
                      if (chk1.checked)
                      {
                        var item = items.getItem(i);
                        var info = item.get_attributes().getAttribute("Count");
                        text += info + ",";
                      }
                    }
  
                    // Remove the last comma from the string.
                    text = removeLastComma(text);
                    //alert("text: " + text);
                    $find("<%= RadAjaxManager1.ClientID %>").ajaxRequest("Status," + text );
                  }
  
                  // This method removes the ending comma from a string.
                  function removeLastComma(str)
                  {
                    str = str.substr(0, str.length - 1);
                    return str;
                  }
  
                  function StopPropagation(e)
                  {
                    // Cancel bubbling.
                    e.cancelBubble = true;
                    if (e.stopPropagation)
                    {
                      e.stopPropagation();
                    }
                    //alert("Stop Propagation done.");
                  }
                </script>
              </telerik:RadScriptBlock>
            </FilterTemplate>
  
          </telerik:GridBoundColumn>
  
          <telerik:GridBoundColumn
            DataField="DNSName"
            AllowFiltering="true"
            FilterControlWidth="150px"
            HeaderText="Computer Name"
            Resizable="true"
            SortExpression="DNSName"
            UniqueName="DNSName"
            >
            <HeaderStyle Width="190px" />
          </telerik:GridBoundColumn>
  
          <telerik:GridBoundColumn
            DataField="CountInstalled"
            AllowFiltering="true"
            FilterControlWidth="34px"
            HeaderText="Installed"
            SortExpression="CountInstalled"
            UniqueName="CountInstalled"
            >
            <HeaderStyle HorizontalAlign="Center" Width="66px" />
            <ItemStyle HorizontalAlign="Center" />
  
            <FilterTemplate>
              <telerik:RadComboBox runat="server"
                ID="RadComboBox2"
                HighlightTemplatedItems="true"
                Width="60"
                >
                <Items>
                  <telerik:RadComboBoxItem Text="" Value="Installed" />
                  <telerik:RadComboBoxItem Text="" Value="Needed" />
                  <telerik:RadComboBoxItem Text="" Value="Not Needed" />
                  <telerik:RadComboBoxItem Text="" Value="Failed" />
                  <telerik:RadComboBoxItem Text="" Value="Unknown" />
                </Items>
                <ItemTemplate>
                  <div onclick="StopPropagation(event)"
                       class="combo-item-template">
                    <asp:CheckBox runat="server" ID="chk2" Checked="true"
                       onclick="onCheckBoxClick_Counts(this)"/>
                    <asp:Label runat="server" ID="Label2"
                        AssociatedControlID="chk2">
                      <span class="NoWrap">
                        <%# DataBinder.Eval(Container, "Value")%>
                      </span>
                    </asp:Label>
                  </div>
                </ItemTemplate>
              </telerik:RadComboBox>
            </FilterTemplate>
  
          </telerik:GridBoundColumn>
  
          <telerik:GridBoundColumn
            DataField="CountNeeded"
            AllowFiltering="false"
            FilterControlWidth="34px"
            HeaderText="Needed"
            SortExpression="CountNeeded"
            UniqueName="CountNeeded"
            >
            <HeaderStyle HorizontalAlign="Center" Width="63px" />
            <ItemStyle HorizontalAlign="Center" />
          </telerik:GridBoundColumn>
  
          <telerik:GridBoundColumn
            DataField="CountNotNeeded"
            AllowFiltering="false"
            FilterControlWidth="34px"
            HeaderText="Not Needed"
            SortExpression="CountNotNeeded"
            UniqueName="CountNotNeeded"
            >
            <HeaderStyle HorizontalAlign="Center" Width="70px" />
            <ItemStyle HorizontalAlign="Center" />
          </telerik:GridBoundColumn>
  
          <telerik:GridBoundColumn
            DataField="CountFailed"
            AllowFiltering="false"
            FilterControlWidth="34px"
            HeaderText="Failed"
            SortExpression="CountFailed"
            UniqueName="CountFailed"
            >
            <HeaderStyle HorizontalAlign="Center" Width="56px" />
            <ItemStyle HorizontalAlign="Center" />
          </telerik:GridBoundColumn>
  
          <telerik:GridBoundColumn
            DataField="CountUnknown"
            AllowFiltering="false"
            FilterControlWidth="34"
            HeaderText="Unknown"
            SortExpression="CountUnknown"
            UniqueName="CountUnknown"
            >
            <HeaderStyle HorizontalAlign="Center" Width="72px" />
            <ItemStyle HorizontalAlign="Center" />
          </telerik:GridBoundColumn>
  
          <telerik:GridBoundColumn
            DataField="ResponsiblePerson"
            AllowFiltering="true"
            AutoPostBackOnFilter="true"
            FilterControlWidth="50px"
            FilterDelay="1000"
            HeaderText="PID"
            SortExpression="ResponsiblePerson"
            UniqueName="ResponsiblePerson"
            >
            <HeaderStyle Width="70px" />
          </telerik:GridBoundColumn>
  
          <telerik:GridBoundColumn
            DataField="SUSClientId"
            UniqueName="SUSClientId"
            Visible="false"
            />
        </Columns>
      </MasterTableView>
  
      <PagerStyle Mode="NextPrevAndNumeric" />
    </telerik:RadGrid>
  </div>
    
  <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/App_Data/RadGrid_SampleData.xml">
  </asp:XmlDataSource>
  
  </form>
</body>
</html>

Default.aspx.cx

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
  
using Telerik.Web.UI;
  
namespace RadGridSample
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
  
  
        #region .  RadAjaxManager1_AjaxRequest()  .
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            string strArgument = e.Argument.ToString();
            string[] astrValues = strArgument.Split(',');
            string[] astrImages = new string[5] { "green", "yellow", "red", "warning", "pending" };
  
            if (astrValues[0] == "Status")
            {
                StringBuilder sbWhere = new StringBuilder();
                for (int i = 1; i < astrValues.Length; i++)
                {
                    sbWhere.Append(String.Format("(Status = \"{0}_{1}_light.gif\") OR ",
                                                    astrValues[i],
                                                    astrImages[i]));
                }
                // Remove trailing " OR ".
                sbWhere.Length -= 4;
  
                string strWhere = sbWhere.ToString();
                string strFilter = RadGrid1.MasterTableView.FilterExpression;
  
                RadGrid1.MasterTableView.FilterExpression = strWhere;
                RadGrid1.Rebind();
            }
  
        }   // RadAjaxManager1_AjaxRequest()
        #endregion
  
  
        #region .  RadGrid1_ItemCommand()  .
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.FilterCommandName)
            {
                Pair oFilterPair = (Pair)e.CommandArgument;
                string strFirst = oFilterPair.First.ToString();
                string strSecond = oFilterPair.Second.ToString();
  
                TextBox txtFilterBox = (e.Item as GridFilteringItem)[strSecond].Controls[0] as TextBox;
  
                string strFilterBoxText = txtFilterBox.Text;
  
                string strCurrentFilterExpression = String.Format("Current Filter Expressioin:  [{0}] {1} {2}",
                                                                    strSecond,
                                                                    strFirst,
                                                                    strFilterBoxText);
            }
  
        }   // RadGrid1_ItemCommand()
        #endregion
  
  
        #region .  RadGrid1_ItemDataBound()  .
        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            try
            {
                if (e.Item is GridPagerItem)
                {
                    // Get the number of rows returned in the data set.
                    int intCountComputers = (e.Item as GridPagerItem).Paging.DataSourceCount;
                }
                else if (e.Item is GridDataItem)
                {
                    GridDataItem oItem = (GridDataItem)e.Item;
  
                    // Setup the stoplight graphic and tooltip.
                    string strCssClass = "";
                    string strStatus = oItem["Status"].Text;
                    string strToolTip = "";
  
                    switch (strStatus.Substring(0, 1))
                    {
                        case "1":   // Green
                            strCssClass = "StatusGreen";
                            strToolTip = "All needed updates installed";
                            break;
                        case "2":   // Yellow
                            strCssClass = "StatusYellow";
                            strToolTip = "Some updates pending install or unknown";
                            break;
                        case "3":   // Red
                            strCssClass = "StatusRed";
                            strToolTip = "Some updates failed";
                            break;
                        case "4":   // Yellow Exclamation Mark
                            strCssClass = "StatusWarning";
                            strToolTip = "Deregistered or timed out";
                            break;
                        case "5":   // Purple
                            strCssClass = "StatusPending";
                            strToolTip = "Waiting for rollup information";
                            break;
                    }
                    oItem["Status"].CssClass = strCssClass;
                    oItem["Status"].ToolTip = strToolTip;
                    oItem["Status"].Text = strStatus.Substring(0, 1);
  
                    // Create the link for the DNS Name column to open the computer
                    // info in a popup window.
                    oItem["DNSName"].Text =
                        String.Format("<a href=\"JavaScript: ShowComputer('{0}','{1}')\">{2}</a>",
                                        oItem["SUSClientId"].Text,
                                        "1",
                                        oItem["DNSName"].Text);
  
                    // Get the update counts.
                    int intInstalled = Convert.ToInt32(oItem["CountInstalled"].Text);
                    int intNeeded = Convert.ToInt32(oItem["CountNeeded"].Text);
                    int intNotNeeded = Convert.ToInt32(oItem["CountNotNeeded"].Text);
                    int intFailed = Convert.ToInt32(oItem["CountFailed"].Text);
                    int intUnknown = Convert.ToInt32(oItem["CountUnknown"].Text);
  
  
                    // Check status:  Active, Inactive, Deregistered.
                    string strActive = oItem["IsActive"].Text;
                    switch (strActive)
                    {
                        case "":
                        case "1":
                            oItem["IsActive"].Text = (strActive == "" ? "(Active)" : "Active");
  
                            // Set the font color for the days ago field.
                            string strColorDaysAgo = "";
                            string strDaysAgo = oItem["DaysAgo"].Text;
                            if (strDaysAgo.StartsWith("Not"))
                            {
                                strColorDaysAgo = " ColorRed";
                                oItem["DaysAgo"].CssClass = strColorDaysAgo;
                            }
                            else if (strDaysAgo.IndexOf(" ") != -1)
                            {
                                int intDaysAgo = int.Parse(strDaysAgo.Substring(0, strDaysAgo.IndexOf(" ")));
                                if ((intDaysAgo > 1) && (intDaysAgo < 8))
                                    strColorDaysAgo = " ColorYellow";
                                else if (intDaysAgo > 8)
                                    strColorDaysAgo = " ColorRed";
                                oItem["DaysAgo"].CssClass = strColorDaysAgo;
                            }
  
                            // Set the font colors for the update counts fields.
                            if (intInstalled != 0) oItem["CountInstalled"].CssClass += " ColorGreen";
                            if (intNeeded != 0) oItem["CountNeeded"].CssClass += " ColorYellow";
                            if (intNotNeeded != 0) oItem["CountNotNeeded"].CssClass += " ColorYellow";
                            if (intFailed != 0) oItem["CountFailed"].CssClass += " ColorRed";
                            if (intUnknown != 0) oItem["CountUnknown"].CssClass += " ColorYellow";
                            break;
  
                        case "0":
                            oItem["DNSName"].CssClass = "GrayLink";
                            oItem["IsActive"].Text = "Deregistered";
                            oItem.Font.Italic = true;
                            oItem.ForeColor = Color.FromArgb(255, 140, 140, 140);
                            break;
  
                        case "-1":
                            oItem["DNSName"].CssClass = "GrayLink";
                            oItem["IsActive"].Text = "Timed Out";
                            oItem.Font.Italic = true;
                            oItem.ForeColor = Color.FromArgb(255, 140, 140, 140);
                            break;
                    }
  
  
                }
            }
            catch (Exception ex)
            {
            }
  
        }   //RadGrid1_ItemDataBound()
        #endregion
  
  
        #region .  RadGrid1_PreRender()  .
        protected void RadGrid1_PreRender(object sender, EventArgs e)
        {
            if (ViewState["filterRawString"] != null)
            {
                foreach (GridFilteringItem item in RadGrid1.MasterTableView.GetItems(GridItemType.FilteringItem))
                {
                    RadComboBox combo = (RadComboBox)item.FindControl("RadComboBox1");
                    foreach (RadComboBoxItem comboItem in combo.Items)
                    {
                        if (ViewState["filterRawString"].ToString().Contains(comboItem.Text.ToString()))
                        {
                            CheckBox chk = (CheckBox)comboItem.FindControl("chk1");
                            chk.Checked = true;
                        }
                        else
                        {
                            CheckBox chk = (CheckBox)comboItem.FindControl("chk1");
                            chk.Checked = false;
                        }
                    }
                }
            }
  
        }   // RadGrid1_PreRender()
        #endregion
  
    }
}

Can you provide a sample of how to make this work?

Thanks,

Randall Price
Senior Programmer Analyst
Virginia Tech
1700 Pratt Drive
Blacksburg, VA  24061

 

1 Answer, 1 is accepted

Sort by
0
Daniel
Telerik team
answered on 10 Aug 2010, 02:12 PM
Hello Randall,

Straight to your questions:

How do I add the "OK" and "Cancel" buttons to the template?
You could use the FooterTemplate for a placeholder

How do I apply the results of the CheckBoxes in the CheckBoxList to the RadGrid filter functionality?
Here is a possible approach:
- in the client-side click event handler build a custom string that contains the necessary data to apply the desired filter
- fire a custom command and pass the aforementioned string (as argument) to the server
- apply the filter expressions manually and then rebind RadGrid

Regards,
Daniel
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
Tags
Grid
Asked by
Randall
Top achievements
Rank 2
Answers by
Daniel
Telerik team
Share this question
or