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

RadGrid drop down custom filter

13 Answers 1780 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Angie
Top achievements
Rank 1
Angie asked on 16 May 2008, 07:59 PM
I'm trying to set up custom filtering in the radgrid.  I've read through the documentation and the examples and have had a hard time piecing them together.  Each example seems to have different code and I can't really comprehend them or get them to work. 

What I want it to look like is:
http://www.telerik.com/demos/aspnet/Grid/Examples/Programming/FilteringTemplateColumns/DefaultCS.aspx  but this code has no c# or vb code, so it's not very usable. 

I found this simple example in one of the forum threads, and it works well in displaying the dropdown list with the data populated, however I cannot get the  combo_SelectedIndexChanged event to fire. 

Here's the applicable code behind:
    protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)  
    {  
 
          
 
        if (e.Item is GridFilteringItem)  
        {  
            GridFilteringItem item = (GridFilteringItem)e.Item;  
            item["loc"].Controls.Clear();  
            RadComboBox combo = new RadComboBox();  
            combo.ID = "RadComboBox1";  
 
            combo.Items.Add(new RadComboBoxItem("", ""));  
            combo.Items.Add(new RadComboBoxItem("Main Page", "1"));  
            combo.Items.Add(new RadComboBoxItem("Left Nav", "2"));  
            combo.AutoPostBack = true;  
            combo.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(combo_SelectedIndexChanged);  
            item["loc"].Controls.Add(combo);  
 
 
 
            //RadAjaxManager1.AjaxSettings.AddAjaxSetting(combo,RadGrid1);  
 
        }    
 
    }  
 
    void combo_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)  
    {  
        RadComboBox combo = (RadComboBox)sender;  
        RadGrid1.MasterTableView.FilterExpression = "([loc_id] = '" + combo.SelectedValue + "') ";  
        GridColumn column = RadGrid1.MasterTableView.GetColumnSafe("loc");  
        column.CurrentFilterFunction = GridKnownFunction.EqualTo;  
 
 
        RadGrid1.Rebind();  
    }   

Here is the aspx code for the grid:

 <telerik:RadAjaxManager EnableAJAX="true" ID="RadAjaxManager1" runat="server">    
        <AjaxSettings>    
            <telerik:AjaxSetting AjaxControlID="RadGrid1">    
                <UpdatedControls>    
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />    
                </UpdatedControls>    
            </telerik:AjaxSetting>    
            <telerik:AjaxSetting AjaxControlID="Button1">    
                <UpdatedControls>    
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />    
                </UpdatedControls>    
            </telerik:AjaxSetting>    
        </AjaxSettings>    
    </telerik:RadAjaxManager>   
 
      
    <telerik:RadGrid ID="RadGrid1" runat="server" OnItemDataBound="RadGrid1_ItemDataBound" 
        AllowFilteringByColumn="True" AllowSorting="True"   
        GridLines="None" Skin="Office2007" Width="400px"   
        OnNeedDataSource="RadGrid1_NeedDataSource"   
        OnUpdateCommand="RadGrid1_UpdateCommand" OnInsertCommand="RadGrid1_InsertCommand" 
        OnItemCommand="RadGrid1_ItemCommand" 
    > 
 
        <MasterTableView autogeneratecolumns="False" AllowFilteringByColumn="True" commanditemdisplay="Top" editmode="InPlace" DataKeyNames="zone_id"  > 
            <RowIndicatorColumn Visible="False">  
            <HeaderStyle Width="20px"></HeaderStyle> 
            </RowIndicatorColumn> 
 
            <ExpandCollapseColumn Visible="False" Resizable="False">  
            <HeaderStyle Width="20px"></HeaderStyle> 
            </ExpandCollapseColumn> 
 
        <Columns> 
            <telerik:GridEditCommandColumn> 
            </telerik:GridEditCommandColumn> 
            <telerik:GridCheckBoxColumn DataField="status" DataType="System.Boolean" ItemStyle-HorizontalAlign="Center" 
                HeaderText="status" SortExpression="status" UniqueName="status" > 
                <ItemStyle HorizontalAlign="Center"></ItemStyle> 
            </telerik:GridCheckBoxColumn> 
            <telerik:GridBoundColumn DataField="order_by" DataType="System.Int32" ItemStyle-Width="30px" 
                HeaderText="order_by" SortExpression="order_by" UniqueName="order_by"   
                AllowFiltering="False">  
                <ItemStyle Width="30px"></ItemStyle> 
            </telerik:GridBoundColumn> 
            <telerik:GridTemplateColumn HeaderText="Category Name"   
                SortExpression="category_name" UniqueName="category_name"   
                AllowFiltering="False"  > 
                <ItemTemplate> 
                    <asp:Label runat="server" ID="lbCategory" Text='<%#Eval("category_name") %>' /> 
                </ItemTemplate> 
                <EditItemTemplate> 
                    <asp:DropDownList ID="ddlCategory" runat="server" Width="150px" /> 
                </EditItemTemplate> 
            </telerik:GridTemplateColumn> 
            <telerik:GridBoundColumn DataField="zone_id" DataType="System.Int32" 
                HeaderText="zone_id" ReadOnly="True" SortExpression="zone_id"   
                UniqueName="zone_id" Display="false" > 
            </telerik:GridBoundColumn> 
            <telerik:GridBoundColumn DataField="loc_id" DataType="System.Int32"    
                HeaderText="loc_id" SortExpression="loc_id" UniqueName="loc_id" Display="false" > 
            </telerik:GridBoundColumn> 
            <telerik:GridBoundColumn DataField="loc" HeaderText="loc" ItemStyle-Width="60px" 
                SortExpression="loc" UniqueName="loc" ReadOnly="True" AllowFiltering="False">  
                <ItemStyle Width="60px"></ItemStyle> 
            </telerik:GridBoundColumn> 
            <telerik:GridBoundColumn DataField="id_type" HeaderText="id_type" ItemStyle-Width="60px" 
                SortExpression="id_type" UniqueName="id_type" ReadOnly="true">  
                <ItemStyle Width="60px"></ItemStyle> 
            </telerik:GridBoundColumn> 
            <telerik:GridBoundColumn DataField="category_id" DataType="System.Int32"   
                HeaderText="category_id" SortExpression="category_id" UniqueName="category_id"   
                Display="false">  
            </telerik:GridBoundColumn> 
            <telerik:GridBoundColumn DataField="site_name" HeaderText="site_name" ReadOnly="true" 
                SortExpression="site_name" UniqueName="site_name">  
            </telerik:GridBoundColumn> 
              <telerik:GridBoundColumn DataField="site_id" DataType="System.Int32"   
                HeaderText="site_id" SortExpression="site_id" UniqueName="site_id"   
                Visible="False">  
            </telerik:GridBoundColumn> 
              
              
              
 
                  
        </Columns> 
 
      
 
<EditFormSettings EditFormType="WebUserControl" UserControlName="AdminUC/BannerZoneInsert.ascx">  
<EditColumn UniqueName="EditCommandColumn1"></EditColumn> 
 
<PopUpSettings ScrollBars="None"></PopUpSettings> 
</EditFormSettings> 
</MasterTableView> 
    </telerik:RadGrid> 

Please note I have the "allowfiltering=false" set in the "loc" column to prevent the viewstate errors that occur when manually adding a filter control.  Also, this grid is ajax-enabled, do I need to somehow add the combo box control to the ajax events?  If so, how would I do that.

Am I missing something else to get this code to work?  Or is it impossible to have custom filters without using that MyCustomFilteringColumn class.  And if I must use that class, can someone please provide a thorough example along the lines of what I have up there, with kind of an explanation?  I would really appreciate it. 

It's been kind of frustrating trying to wade through all the disparate documentation to get a working product.   I would appreciate some direction.

Thanks!

-Angie

13 Answers, 1 is accepted

Sort by
0
Sebastian
Telerik team
answered on 19 May 2008, 12:19 PM
Hi Angie,

I am sorry to hear that you are having hard time trying to configure your grid instance with dropdown filters.

The proper method to implement filtering with RadComboBox for your GridBoundColumn (with DataField named 'loc') is to extend the column in a custom class as shown here and insert the dropdown instance in the SetupFilterControls() method. Then handle the SelectedIndexChanged event of the combobox and invoke the FireCommandEvent method of the grid to perform the corresponding filter action.

For further details review the sample project from the forum thread linked below:

http://www.telerik.com/community/forums/thread/b311D-ecghh.aspx

and convert it to use RadGrid for ASP.NET AJAX having in mind the details outlined in this documentation topic.

Best regards,
Stephen
the Telerik team

Instantly find answers to your questions at the new Telerik Support Center
0
Angie
Top achievements
Rank 1
answered on 20 May 2008, 04:09 PM
Stephen, thanks for responding.  Once I got it narrowed down to using the Custom Class it became a little clearer. 

The example for setting up mulitple filters was the most applicable, but I did not need to handle the column created or column equal events.
http://www.telerik.com/help/aspnet/grid/grdfilteringwithdropdownlist.html

Really all I had to do was assign the dropdown datasources on the NeedDataSource event and the custom class handled it from there.

protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)  
    {  
        DataSet ds = FarranMedia.Classes.BannerZones.GetBannerZonesAll();  
        RadGrid1.DataSource = ds.Tables[0];  
 
        foreach (GridColumn column in RadGrid1.MasterTableView.Columns)  
        {  
            if (column.ColumnType.ToString().ToLower().IndexOf("customfiltering") != -1)  
            {  
                switch (column.UniqueName.ToLower())  
                {  
                      
                    case "location":  
                        RadGrid.TelerikCustomFilteringBoundColumn location = (RadGrid.TelerikCustomFilteringBoundColumn)column;  
 
                        DataTable dtLoc = new DataTable("Locations");  
                        dtLoc.Columns.Add("loc", Type.GetType("System.String"));  
 
                        DataRow drBlank = dtLoc.NewRow();  
                        drBlank["loc"] = "";  
                        dtLoc.Rows.Add(drBlank);  
 
                        DataRow drLoc = dtLoc.NewRow();  
                        drLoc["loc"] = "Main Page";  
                        dtLoc.Rows.Add(drLoc);  
 
                        DataRow drLoc2 = dtLoc.NewRow();  
                        drLoc2["loc"] = "Left Nav";  
                        dtLoc.Rows.Add(drLoc2);  
 
                        location.ListDataSource = dtLoc;  
                        break;  
 
                    case "id_type":  
                        RadGrid.TelerikCustomFilteringBoundColumn idType = (RadGrid.TelerikCustomFilteringBoundColumn)column;  
                          
                        DataTable dtID = new DataTable("id_type");  
                        dtID.Columns.Add("id_type", Type.GetType("System.String"));  
 
                        DataRow drBlankID = dtID.NewRow();  
                        drBlankID["id_type"] = "";  
                        dtID.Rows.Add(drBlankID);  
 
                        DataRow drID = dtID.NewRow();  
                        drID["id_type"] = "site";  
                        dtID.Rows.Add(drID);  
 
                        DataRow drID2 = dtID.NewRow();  
                        drID2["id_type"] = "category";  
                        dtID.Rows.Add(drID2);  
 
                        idType.ListDataSource = dtID;  
                        break;  
 
                    case "status":  
                        RadGrid.TelerikCustomFilteringTemplateColumn status = (RadGrid.TelerikCustomFilteringTemplateColumn)column;  
                        status.TrueText = "Active";  
                        status.FalseText = "Inactive";  
                        break;  
                  
 
                } 


I also modified the custom class to handle checkboxes by automatically building a true/false dropdown in case anyone is interested.

using System.Data;  
using System.Configuration;  
using Telerik.Web.UI;  
using System.Web.UI.WebControls;  
using System.Web.UI;  
using System;  
using System.Collections;  
 
namespace RadGrid  
{  
    public class TelerikCustomFilteringTemplateColumn : GridTemplateColumn  
    {  
 
        //Properties for boolean/checkbox dropdown  
        public string TrueText {get;set;}  
        public string FalseText { get; set; }  
 
        private object listDataSource = null;  
 
        //RadGrid will call this method when it initializes the controls inside the filtering item cells  
        protected override void SetupFilterControls(TableCell cell)  
        {  
            base.SetupFilterControls(cell);  
            cell.Controls.RemoveAt(0);  
 
            System.Web.UI.WebControls.DropDownList list = new System.Web.UI.WebControls.DropDownList();  
            list.ID = "list" + this.DataField;  
 
            list.Height = Unit.Pixel(300);  
            list.AutoPostBack = true;  
 
            list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);  
 
            cell.Controls.AddAt(0, list);  
            cell.Controls.RemoveAt(1);  
 
            //If boolean, assume CHECKBOX  
            if (this.DataType.ToString() == "System.Boolean")  
            {  
                DataTable dtBool = new DataTable();  
                dtBool.Columns.Add(this.DataField, Type.GetType("System.Boolean"));  
                dtBool.Columns.Add("description", Type.GetType("System.String"));  
 
                //Blank row  
                DataRow drBlank = dtBool.NewRow();  
                drBlank["description"] = "";  
                dtBool.Rows.Add(drBlank);  
 
                //Checked row  
                DataRow drTrue = dtBool.NewRow();  
                drTrue["description"] = TrueText;  
                drTrue[this.DataField] = 1;  
                dtBool.Rows.Add(drTrue);  
 
                //Unchecked row  
                DataRow drFalse = dtBool.NewRow();  
                drFalse["description"] = FalseText;  
                drFalse[this.DataField] = 0;  
                dtBool.Rows.Add(drFalse);  
 
                list.DataSource = dtBool;  
                list.DataTextField = "description";  
                list.DataValueField = this.DataField;  
                list.DataBind();  
 
            }  
            else  
            {  
                list.DataTextField = this.DataField;  
                list.DataValueField = this.DataField;  
 
                list.DataSource = this.ListDataSource;  
                list.DataBind();  
            }  
 
        }  
 
        void list_SelectedIndexChanged(object sender, EventArgs e)  
        {  
            GridFilteringItem filterItem = (sender as DropDownList).NamingContainer as GridFilteringItem;  
 
            this.SelectedValue = (sender as DropDownList).SelectedValue;  
            thisthis.FilteredColumnName = this.UniqueName;  
 
            if (this.UniqueName == "Index" || this.DataType.ToString() == "System.Boolean")  
            {  
                //this is example for filtering for integer column type  
                filterItem.FireCommandEvent("Filter", new Pair("EqualTo", this.UniqueName));  
            }  
            //filtering for string column type  
            filterItem.FireCommandEvent("Filter", new Pair("Contains", this.UniqueName));  
 
        }  
        public object ListDataSource  
        {  
            get  
            {  
                return this.listDataSource;  
            }  
            set  
            {  
                listDataSource = value;  
            }  
        }  
        public string SelectedValue  
        {  
            get  
            {  
                object res = this.Owner.OwnerGrid.Page.Session["SelectedValue"];  
                if (res != null)  
                {  
                    return (string)res;  
                }  
                return "";  
            }  
            set  
            {  
                this.Owner.OwnerGrid.Page.Session["SelectedValue"] = value;  
            }  
        }  
        public string FilteredColumnName  
        {  
            get  
            {  
                object res = this.Owner.OwnerGrid.Page.Session["FilteredColumnName"];  
                if (res != null)  
                {  
                    return (string)res;  
                }  
                return "";  
            }  
            set  
            {  
                this.Owner.OwnerGrid.Page.Session["FilteredColumnName"] = value;  
            }  
        }  
        //RadGrid will call this method when the value should be set to the filtering input control(s)  
        protected override void SetCurrentFilterValueToControl(TableCell cell)  
        {  
            base.SetCurrentFilterValueToControl(cell);  
 
            System.Web.UI.WebControls.DropDownList list = (System.Web.UI.WebControls.DropDownList)cell.Controls[0];  
            if (this.CurrentFilterValue != string.Empty)  
            {  
                list.SelectedValue = this.CurrentFilterValue;  
            }  
        }  
 
        //RadGrid will call this method when the filtering value should be extracted from the filtering input control(s)  
        protected override string GetCurrentFilterValueFromControl(TableCell cell)  
        {  
            System.Web.UI.WebControls.DropDownList list = (System.Web.UI.WebControls.DropDownList)cell.Controls[0];  
 
            return list.SelectedValue;  
        }  
        public override GridColumn Clone()  
        {  
            return base.Clone();  
        }  
        protected override string GetFilterDataField()  
        {  
            return this.DataField;  
        }  
 
    }  


Thanks!

-Angie
0
Justin
Top achievements
Rank 1
answered on 13 Aug 2008, 02:14 AM
I am having a lot of problems with custom filtering rad grid - I have tried just about every "official" example on the Telerik website that I could find.

The following "work", but result in an error when selecting an item in the drop down list to filter on:


When selecting an option from the drop down list I get the "Object Reference not sent to an Instance of an Object" error on the following line:

filterItem.FireCommandEvent(

"Filter", new Pair("Contains", this.UniqueName));

Any thoughts as to what might be causing this?

Justin

0
Vlad
Telerik team
answered on 13 Aug 2008, 04:47 AM
Hello Justin,

You can check this example:
http://www.telerik.com/DEMOS/ASPNET/Prometheus/Grid/Examples/Programming/FilteringTemplateColumns/DefaultCS.aspx

Sincerely yours,
Vlad
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Justin
Top achievements
Rank 1
answered on 13 Aug 2008, 10:43 PM
Vlad - appreciate the pointer, however I have already gone through that to no avail.  If I use that one selecting an item from the drop down box does not result in the error mentioned earlier - but it also does not do any filtering...

Definately confused on this one :)
0
Vlad
Telerik team
answered on 14 Aug 2008, 05:37 AM
Hi Justin,

I just tried our online example and everything worked fine on my end.

Regards,
Vlad
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
James
Top achievements
Rank 1
answered on 05 Sep 2008, 07:02 PM
Do you have a complete eample of this? I am having the same challenge and the examples that Telerik are supplying are lacking.

Thank you in advance.
0
Sebastian
Telerik team
answered on 08 Sep 2008, 08:17 AM
Hello James,

You can find a sample project using the Classic version of RadGrid in this public forum post:

http://www.telerik.com/community/forums/thread/b311D-ecghh.aspx

In order to port the code to the ASP.NET AJAX counterpart of the control follow the steps from the documentation article linked below:

http://www.telerik.com/help/aspnet-ajax/grdmigrationtoprometheus.html

Furthermore, note that you can find a mirror version of the "Filtering template columns" online demo of the product in your local installation of RadControls for ASP.NET AJAX (under the location pointed here):

C:\Program Files\telerik\RadControls for ASPNET AJAX Q2 2008\Live Demos\Grid\Examples\Programming\FilteringTemplateColumns

Best regards,
Stephen
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Dave
Top achievements
Rank 1
answered on 11 Sep 2008, 06:26 PM
Justin and James -
I am getting the exact error ("Object Reference not sent to an Instance of an Object") when calling the FireCommandEvent function from my custom filter class.  How did you resolve it?

Thanks,
Dave
0
Vlad
Telerik team
answered on 12 Sep 2008, 06:16 AM
Hello Dave,

Can you verify using the debugger which object is null in your case?

Best wishes,
Vlad
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Dave
Top achievements
Rank 1
answered on 12 Sep 2008, 03:34 PM
I can't tell exactly which object is null, but here is the info that the debugger spit out:

Source: Anonymously Hosted DynamicMethods Assembly

Stack Trace:
   at lambda_method(ExecutionScope , VB$AnonymousType_0`7 )  
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()  
   at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)  
   at lambda_method(ExecutionScope )  
   at System.Linq.EnumerableExecutor`1.Execute()  
   at System.Linq.EnumerableExecutor`1.ExecuteBoxed()  
   at System.Linq.EnumerableQuery`1.System.Linq.IQueryProvider.Execute(Expression expression)  
   at Telerik.Web.UI.GridDynamicQueryable.Count(IQueryable source)  
   at Telerik.Web.UI.GridDataTableFromEnumerable.FillData35()  
   at Telerik.Web.UI.GridDataTableFromEnumerable.FillData()  
   at Telerik.Web.UI.GridResolveEnumerable.Initialize()  
   at Telerik.Web.UI.GridResolveEnumerable.EnsureInitialized()  
   at Telerik.Web.UI.GridResolveEnumerable.get_DataTable()  
   at Telerik.Web.UI.GridEnumerableFromDataView..ctor(GridTableView owner, IEnumerable enumerable, Boolean CaseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields)  
   at Telerik.Web.UI.GridDataSourceHelper.CreateGridEnumerable(GridTableView owner, IEnumerable enumerable, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields)  
   at Telerik.Web.UI.GridDataSourceHelper.GetResolvedDataSource(GridTableView owner, Object dataSource, String dataMember, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields)  
   at Telerik.Web.UI.GridTableView.get_ResolvedDataSource()  
   at Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource)  
   at System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data)  
   at System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data)  
   at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback)  
   at System.Web.UI.WebControls.DataBoundControl.PerformSelect()  
   at Telerik.Web.UI.GridTableView.PerformSelect()  
   at System.Web.UI.WebControls.BaseDataBoundControl.DataBind()  
   at Telerik.Web.UI.GridTableView.DataBind()  
   at Telerik.Web.UI.GridTableView.Rebind()  
   at Telerik.Web.UI.GridFilterCommandEventArgs.ExecuteCommand(Object source)  
   at Telerik.Web.UI.RadGrid.OnBubbleEvent(Object source, EventArgs e)  
   at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)  
   at Telerik.Web.UI.GridItem.OnBubbleEvent(Object source, EventArgs e)  
   at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)  
   at Telerik.Web.UI.GridItem.OnBubbleEvent(Object source, EventArgs e)  
   at Telerik.Web.UI.GridItem.FireCommandEvent(String commandName, Object commandArgument)  
   at Telerik.Grid.Programming.FilteringTemplateColumns.DeptNameCustomFilteringColumn.list_SelectedIndexChanged(Object o, RadComboBoxSelectedIndexChangedEventArgs e) in C:\Projects\CKB\WebSite\App_Code\DeptNameCustomFilteringColumn.vb:line 73  
   at Telerik.Web.UI.RadComboBox.RaiseSelectedIndexChandedEvent()  
   at Telerik.Web.UI.RadComboBox.RaisePostDataChangedEvent()  
   at Telerik.Web.UI.RadDataBoundControl.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent()  
   at System.Web.UI.Page.RaiseChangedEvents()  
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 

Target Site: {System.Reflection.Emit.DynamicMethod.RTDynamicMethod}

The nullreferenceexception is thrown on the following line of code:
 filterItem.FireCommandEvent("Filter", New Pair("Contains", Me.UniqueName)) 

Here is the sub that that particular line of code is in:
        Private Sub list_SelectedIndexChanged(ByVal o As Object, ByVal e As Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs)  
            Dim filterItem As GridFilteringItem = CType(CType(o, RadComboBox).NamingContainer, GridFilteringItem)  
            If (Me.UniqueName = "Index") Then  
                'this is filtering for integer column type   
                filterItem.FireCommandEvent("Filter", New Pair("EqualTo", Me.UniqueName))  
            End If  
            'filtering for string column type  
            filterItem.FireCommandEvent("Filter", New Pair("Contains", Me.UniqueName))  
        End Sub 

In the debugger, I inspected the filterItem variable in the SelectedIndexChanged event and it looks like the RowIndex is null at the time the exception is thrown. The stack trace for the RowIndex object says:  at Telerik.Web.UI.GridItem.get_RowIndex().

Here is the code for my custom filtering class:

DeptNameCustomFilteringColumn.vb
Imports Microsoft.VisualBasic  
Imports System.Data  
Imports Telerik.Web.UI  
Imports DataWarehouse  
Imports System.Windows.Forms  
 
Namespace Telerik.Grid.Programming.FilteringTemplateColumns  
    Public Class DeptNameCustomFilteringColumn  
        Inherits GridTemplateColumn  
 
        'RadGrid will cal this method when it initializes the controls inside the filtering item cells  
        Protected Overrides Sub SetupFilterControls(ByVal cell As TableCell)  
            MyBase.SetupFilterControls(cell)  
            cell.Controls.RemoveAt(0)  
            Dim combo As RadComboBox = New RadComboBox  
            combo.ID = ("RadComboBox1" + Me.DataField)  
            combo.ShowToggleImage = False 
            combo.Skin = "Sunset" 
            combo.EnableLoadOnDemand = True 
            combo.AutoPostBack = True 
            combo.MarkFirstMatch = True 
            combo.Height = Unit.Pixel(100)  
            combo.Width = Unit.Pixel(100)  
            AddHandler combo.ItemsRequested, AddressOf Me.list_ItemsRequested  
            AddHandler combo.SelectedIndexChanged, AddressOf Me.list_SelectedIndexChanged  
            cell.Controls.AddAt(0, combo)  
            cell.Controls.RemoveAt(1)  
        End Sub  
 
        'RadGrid will cal this method when the value should be set to the filtering input control(s)  
        Protected Overrides Sub SetCurrentFilterValueToControl(ByVal cell As TableCell)  
            MyBase.SetCurrentFilterValueToControl(cell)  
            Dim combo As RadComboBox = CType(cell.Controls(0), RadComboBox)  
            If (Me.CurrentFilterValue <> String.Empty) Then  
                combo.Text = Me.CurrentFilterValue  
            End If  
        End Sub  
 
        'RadGrid will cal this method when the filtering value should be extracted from the filtering input control(s)  
        Protected Overrides Function GetCurrentFilterValueFromControl(ByVal cell As TableCell) As String  
            Dim combo As RadComboBox = CType(cell.Controls(0), RadComboBox)  
            Return combo.Text  
        End Function  
 
        Private Sub list_ItemsRequested(ByVal o As Object, ByVal e As RadComboBoxItemsRequestedEventArgs)  
            CType(o, RadComboBox).DataTextField = Me.DataField  
            CType(o, RadComboBox).DataValueField = Me.DataField  
 
            Dim dtDepts As New DataTable  
            dtDepts = GetDataTable()  
            Dim drArrFiltered As DataRow() = dtDepts.Select("deptNames LIKE '" & e.Text & "%'")  
 
            Dim dtFiltered As New DataTable  
            dtFiltered = dtDepts.Clone  
 
            For Each row As DataRow In drArrFiltered  
                Dim newRow As DataRow = dtFiltered.NewRow  
                newRow("deptNames") = row.Item(0)  
                dtFiltered.Rows.Add(newRow)  
            Next  
 
            CType(o, RadComboBox).DataSource = dtFiltered 
            CType(o, RadComboBox).DataBind()  
        End Sub  
 
        Private Sub list_SelectedIndexChanged(ByVal o As Object, ByVal e As Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs)  
            Dim filterItem As GridFilteringItem = CType(CType(o, RadComboBox).NamingContainer, GridFilteringItem)  
            If (Me.UniqueName = "Index") Then  
                'this is filtering for integer column type   
                filterItem.FireCommandEvent("Filter", New Pair("EqualTo", Me.UniqueName))  
            End If  
            'filtering for string column type  
            filterItem.FireCommandEvent("Filter", New Pair("Contains", Me.UniqueName))  
        End Sub  
 
        Public Shared Function GetDataTable() As DataTable  
 
            Dim dTbl As New DataTable  
 
            Dim DeptName As DataColumn = New DataColumn("deptNames")  
            DeptName.DataType = System.Type.GetType("System.String")  
            dTbl.Columns.Add(DeptName)  
 
            Dim dwh As New APLDataWarehouse  
 
            For Each validdept As OrganizationUnit In dwh.GetDepartments  
                Dim newRow As DataRow = dTbl.NewRow  
                newRow.Item(0) = validdept.Abbreviation  
                dTbl.Rows.Add(newRow)  
            Next  
 
            dTbl.AcceptChanges()  
 
            Return dTbl  
 
        End Function  
    End Class  
End Namespace  
 

Here is how I declare the custom column in my aspx page:

                        <custom:DeptNameCustomFilteringColumn DataField="deptNames" HeaderText="Department" UniqueName="deptNames" SortExpression="deptNames">  
                            <ItemTemplate> 
                                <asp:Label ID="lblDN" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.deptNames") %>'></asp:Label>                            
                            </ItemTemplate> 
                        </custom:DeptNameCustomFilteringColumn>    

Here is the rest of the code for that particular RadGrid:
            <telerik:RadGrid ID="rgTransactions" runat="server" Skin="Sunset"   
                AllowFilteringByColumn="True" AllowPaging="True" AllowSorting="True"   
                GridLines="None" AutoGenerateColumns="false" Width="98%">  
                <MasterTableView DataKeyNames="transID" NoMasterRecordsText="There are currently no transactions to display">  
                    <RowIndicatorColumn Visible="False">  
                        <HeaderStyle Width="20px" /> 
                    </RowIndicatorColumn> 
                    <ExpandCollapseColumn Resizable="False" Visible="False">  
                        <HeaderStyle Width="20px" /> 
                    </ExpandCollapseColumn> 
                    <Columns> 
                        <telerik:GridButtonColumn CommandName="Select" UniqueName="column2" Text="View Details">  
                        </telerik:GridButtonColumn> 
                          
                        <custom:LeadAnalystCustomFilteringColumn DataField="leadAnalystName" HeaderText="Lead Analyst" UniqueName="leadAnalystName" SortExpression="leadAnalystName">  
                            <ItemTemplate> 
                                <asp:Label ID="lblLA" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.leadAnalystName") %>'></asp:Label> 
                            </ItemTemplate> 
                        </custom:LeadAnalystCustomFilteringColumn> 
                      
                        <telerik:GridDateTimeColumn DataField="dateOfTransaction" HeaderText="Trans. Date"   
                            SortExpression="dateOfTransaction" AllowFiltering="false" DataFormatString="{0:d}">  
                        </telerik:GridDateTimeColumn>    
                           
                        <telerik:GridDateTimeColumn DataField="dateNeeded" HeaderText="Date Needed"   
                            SortExpression="dateNeeded" DataFormatString="{0:d}" UniqueName="dateNeeded" DataType="System.DateTime" FilterListOptions="VaryByDataType">  
                        </telerik:GridDateTimeColumn>                  
 
                        <custom:TransStatusCustomFilteringColumn DataField="transactionStatusName" HeaderText="Trans. Status" UniqueName="transactionStatusName" SortExpression="transactionStatusName">  
                            <ItemTemplate> 
                                <asp:Label ID="lblTS" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "transactionStatusName") %>'></asp:Label>                            
                            </ItemTemplate> 
                        </custom:TransStatusCustomFilteringColumn> 
                                                    
                        <telerik:GridBoundColumn DataField="request" HeaderText="Request"   
                            SortExpression="request" DataType="System.String" UniqueName="request" FilterListOptions="VaryByDataType">  
                        </telerik:GridBoundColumn>   
                          
                        <custom:DeptNameCustomFilteringColumn DataField="deptNames" HeaderText="Department" UniqueName="deptNames" SortExpression="deptNames">  
                            <ItemTemplate> 
                                <asp:Label ID="lblDN" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.deptNames") %>'></asp:Label>                            
                            </ItemTemplate> 
                        </custom:DeptNameCustomFilteringColumn>                          
                             
                        <telerik:GridNumericColumn DataField="transID" HeaderText="Trans. ID" 
                            SortExpression="transID" DataType="System.Int32" UniqueName="transID" FilterListOptions="VaryByDataType">  
                        </telerik:GridNumericColumn>   
                                                                    
                        <telerik:GridButtonColumn CommandName="Delete" ConfirmText="Are you sure you want to delete this transaction?" 
                            ConfirmTitle="Delete Transaction" Text="Delete" UniqueName="column1" HeaderText="Delete">  
                        </telerik:GridButtonColumn> 
                    </Columns> 
                    <EditFormSettings> 
                        <PopUpSettings ScrollBars="None" /> 
                    </EditFormSettings> 
                </MasterTableView> 
            </telerik:RadGrid>   

Here is how the grid gets populated from code-behind:
    Protected Sub rgTransactions_NeedDataSource(ByVal source As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles rgTransactions.NeedDataSource  
        Try  
            FillGrid(False) ' needdatasource takes care of calling databind method so no need to explicitly call databind  
 
        Catch ex As Exception  
            Dim errorObj As New WebErrorHandler  
            errorObj.SendEmailContainingException(ConfigurationManager.AppSettings("ApplicationName").ToString, _  
                                                  ConfigurationManager.AppSettings("AdminEmailAddress").ToString, _  
                                                  ex.Message, _  
                                                  ex.Source, _  
                                                  ex.StackTrace, _  
                                                  GetCurrUserName)  
        End Try  
    End Sub  
 
    Private Sub FillGrid(Optional ByVal BindData As Boolean = True)  
 
        ' build query based on what is currently selected in the 2 external filters  
        Dim dwh As New APLDataWarehouse  
 
        Dim lnqTrans = From trans In db.MainTransactionGrids _  
                       Order By trans.dateOfTransaction Descending _  
                       Where trans.leadID.ToUpper = GetCurrUserName() _  
                       And trans.transactionStatusID <> (From tstat In db.TransactionStatus _  
                                                Where tstat.ValueName = "Deleted" _  
                                                Select tstat.ValueID).Single _  
                       Select New With { _  
                            .leadAnalystName = String.Format("{1}, {0}", dwh.GetPersonByDomainID(trans.leadID).FirstName, dwh.GetPersonByDomainID(trans.leadID).LastName), _  
                            .dateOfTransaction = trans.dateOfTransaction, _  
                            .dateNeeded = trans.dateNeeded, _  
                            .transactionStatusName = (From tstat In db.TransactionStatus _  
                                                      Where tstat.ValueID = trans.transactionStatusID _  
                                                      Select tstat.ValueName).Single, _  
                            .request = If(trans.request.Length > 50, trans.request.Substring(0, 49) & " ...", trans.request), _  
                            .transID = trans.transID, _  
                            .deptNames = trans.deptNames}  
 
        If rblShow.SelectedValue = "all" Then  
            ' user wants to see all transactions so redefine the linq query to not include a predicate on the leadID  
            lnqTrans = From trans In db.MainTransactionGrids _  
               Order By trans.dateOfTransaction Descending _  
               Where trans.transactionStatusID <> (From tstat In db.TransactionStatus _  
                                        Where tstat.ValueName = "Deleted" _  
                                        Select tstat.ValueID).Single _  
               Select New With { _  
                    .leadAnalystName = String.Format("{1}, {0}", dwh.GetPersonByDomainID(trans.leadID).FirstName, dwh.GetPersonByDomainID(trans.leadID).LastName), _  
                    .dateOfTransaction = trans.dateOfTransaction, _  
                    .dateNeeded = trans.dateNeeded, _  
                    .transactionStatusName = (From tstat In db.TransactionStatus _  
                                              Where tstat.ValueID = trans.transactionStatusID _  
                                              Select tstat.ValueName).Single, _  
                    .request = If(trans.request.Length > 50, trans.request.Substring(0, 49) & " ...", trans.request), _  
                    .transID = trans.transID, _  
                    .deptNames = trans.deptNames}  
        End If  
 
        ' filter on the start and end transaction dates specified by user  
        If Not rdpStartDate.IsEmpty Or Not rdpEndDate.IsEmpty Then  
            If Not rdpStartDate.IsEmpty And Not rdpEndDate.IsEmpty Then  
                lnqTrans = From trans In lnqTrans _  
                Where trans.dateOfTransaction >= rdpStartDate.SelectedDate And trans.dateOfTransaction <= rdpEndDate.SelectedDate _  
                Select trans  
            Else  
                If Not rdpStartDate.IsEmpty Then  
                    lnqTrans = From trans In lnqTrans _  
                    Where trans.dateOfTransaction >= rdpStartDate.SelectedDate _  
                    Select trans  
                End If  
 
                If Not rdpEndDate.IsEmpty Then  
                    lnqTrans = From trans In lnqTrans _  
                    Where trans.dateOfTransaction <= rdpEndDate.SelectedDate _  
                    Select trans  
                End If  
            End If  
        End If  
 
        rgTransactions.DataSource = lnqTrans 
        If BindData Then  
            rgTransactions.DataBind()  
        End If  
    End Sub 









0
Nikolay Rusev
Telerik team
answered on 16 Sep 2008, 07:50 AM
Hi Dave ,

I am attaching sample project demonstrating custom filtering column.
From the code you posted I assume that you are using 3.5 as target platform in your project. If so RadGrid Linq expressions are automatically enabled and this might cause the issue in your code. You have two choices
1. set EnableLinqExpressions to false
2. to modify your custom template column to work with enabled Linq expression of RadGrid.

Best wishes,
Nikolay
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Dave
Top achievements
Rank 1
answered on 19 Sep 2008, 02:17 PM
Setting the EnableLinqExpressions property to false worked.  Thanks so much!
Tags
Grid
Asked by
Angie
Top achievements
Rank 1
Answers by
Sebastian
Telerik team
Angie
Top achievements
Rank 1
Justin
Top achievements
Rank 1
Vlad
Telerik team
James
Top achievements
Rank 1
Dave
Top achievements
Rank 1
Nikolay Rusev
Telerik team
Share this question
or