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

How to add gridboundcolum with custom filtertemplate all programmatically

12 Answers 342 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Matt
Top achievements
Rank 1
Matt asked on 13 Apr 2011, 05:33 PM
I am creating a RadGrid completely in code-behind.  I want to use custom FilterTemplates with my GridBoundColumns.  All of the documentation and examples show the columns being added declaritvely in markup, and creating a custom GridTemplateColumn class for the filter template.  How can I add a custom filter template to a GridBoundColumn I'm adding programmatically?  Do I need some combination of an ITemplate implemention and a GridTemplateColumn?

Thanks

Matt A.

12 Answers, 1 is accepted

Sort by
0
Mira
Telerik team
answered on 18 Apr 2011, 03:50 PM
Hello Matt,

In order to implement the desired functionality, I recommend that you follow the Creating template columns programmatically section of the Programmatic creation help topic.
The FilterTemplates of the corresponding columns should be created and assigned dynamically, in the same way as the ItemTemplates and EditTemplates.

I hope this helps.

Best wishes,
Mira
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

0
Andrea
Top achievements
Rank 1
answered on 23 Jul 2011, 07:13 AM
I have the same problem, but in the help I cannot find the solution.
I create MyFilteringColumn : GridTemplateColumn.

I create programmatically the column so
var newColumn = new ClientsTypesFilteringColumn();
Grid.MasterTableView.Columns.Add(newColumn);
newColumn.DataType = detail.DataType
newColumn.UniqueName = detail.DataField;
newColumn.HeaderText = detail.Description; 

When I bind the data the column are empty (if I use a GridBoundColumn, so var newColumn=new GridBoundColumn,  I can see data and I can use standard filter without problem),

Moreover when I'm filtering I got "Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Cannot create column with the specified type name: MyFilteringColumn"

Can you help me?

0
Matt
Top achievements
Rank 1
answered on 25 Jul 2011, 09:24 PM
Andrea,

Without seeing all of the code it's difficult to tell. Be sure you're setting the DataField property, I didn't see that being set in your code snippet.  Also, I wound up using a custom item template (inherting from ITemplate) along with the drop-down filter template.  Here's the code:

The drop-down filter header template:

public class DropDownFilterTemplate : GridTemplateColumn
    {
        private FilterPropertyType _filterProperty = FilterPropertyType.Generic;
  
        public FilterPropertyType FilterProperty
        {
            get { return _filterProperty; }
            set { _filterProperty = value; }
        }
  
        public DropDownFilterTemplate()
        {
              
        }
  
        public override ITemplate ItemTemplate
        {
            get
            {
                return base.ItemTemplate;
            }
            set
            {
                base.ItemTemplate = value;
            }
        }
  
        protected override void SetupFilterControls(TableCell cell)
        {
            RadComboBox comboBox = new RadComboBox();
  
            int comboBoxWidth = 120;
            switch (this._filterProperty)
            {
                case FilterPropertyType.Generic:
                    comboBoxWidth = 120;
                    break;
                case FilterPropertyType.ActivityName:
                    comboBoxWidth = 120;
                    break;
                case FilterPropertyType.AssignedUser:
                    comboBoxWidth = 155;
                    break;
                default:
                    break;
            }
  
            comboBox.Width = new Unit(comboBoxWidth);
            comboBox.ID = string.Format("DropDownList_{0}", this.DataField);
            comboBox.AutoPostBack = true;
            comboBox.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(comboBox_SelectedIndexChanged);
            comboBox.DataBinding += new EventHandler(comboBox_DataBinding);
            comboBox.Skin = "CustomSkin1";
            comboBox.EnableEmbeddedSkins = false;
            cell.Controls.Add(comboBox);
        }        
  
        protected override void SetCurrentFilterValueToControl(TableCell cell)
        {
            if (!string.IsNullOrEmpty(this.CurrentFilterValue))
            {
                if (cell.Controls != null && cell.Controls.Count > 0)
                {
                    RadComboBox comboBox = (RadComboBox)cell.Controls[0];
  
                    if (comboBox != null)
                    {
                        RadComboBoxItem item = comboBox.Items.FindItemByText(this.CurrentFilterValue);
  
                        if (item != null)
                            item.Selected = true;
                    }
                }                
            }
        }
  
        protected override string GetCurrentFilterValueFromControl(TableCell cell)
        {
            string currentValue = ((RadComboBox)cell.Controls[0]).SelectedItem.Value;
            this.CurrentFilterFunction = (currentValue != "") ? GridKnownFunction.EqualTo : GridKnownFunction.NoFilter;
            return currentValue;
        }
  
        void comboBox_DataBinding(object sender, EventArgs e)
        {
            RadComboBox combo = (RadComboBox)sender;            
  
            List<ProcessInstance> instanceList = (List<ProcessInstance>)((RadGrid)combo.NamingContainer.NamingContainer.NamingContainer.NamingContainer).DataSource;
  
            var distinctItems = new List<string>();
  
            if (this._filterProperty == FilterPropertyType.ActivityName)
            {
                distinctItems = ((from p in instanceList
                                  select p.ActiveActivity.ActivityDefinition.ActivityName).Distinct()).ToList();
            }
            else if (this._filterProperty == FilterPropertyType.AssignedUser)
            {
                distinctItems = ((from p in instanceList where p.ActiveActivity.AssignedUser.UserName != string.Empty
                                  select p.ActiveActivity.AssignedUser.UserName).Distinct()).ToList();
            }
            else
            {
                // Generic top level property
                distinctItems = ((from p in instanceList
                                  select (string)p.GetType().GetProperty(this.DataField).GetValue(p, null)).Distinct()).ToList();
            }
  
            combo.Items.Add(new RadComboBoxItem(string.Empty, string.Empty));
  
            foreach (var item in distinctItems)
            {
                combo.Items.Add(new RadComboBoxItem((string)item, (string)item));
            }
  
        }
  
        void comboBox_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            ((GridFilteringItem)(((RadComboBox)sender).Parent.Parent)).FireCommandEvent("Filter", new Pair());
        }
  
    }

The column template:

public class BasicTextColumnTemplate : ITemplate
    {
        Label _label;
        string _propertyName;
  
        private FilterPropertyType _filterProperty = FilterPropertyType.Generic;
  
        public FilterPropertyType FilterProperty
        {
            get { return _filterProperty; }
            set { _filterProperty = value; }
        }
  
        public BasicTextColumnTemplate(string propertyName)
        {
            _propertyName = propertyName;
        }
  
        public void InstantiateIn(System.Web.UI.Control container)
        {
            _label = new Label();
            _label.DataBinding += new EventHandler(_literalText_DataBinding);
            container.Controls.Add(_label);
        }
  
        void _literalText_DataBinding(object sender, EventArgs e)
        {
            Label label = (Label)sender;
            GridDataItem container = (GridDataItem)label.NamingContainer;
  
            ProcessInstance instance = (ProcessInstance)container.DataItem;
            string value;
  
            if (this._filterProperty == FilterPropertyType.AssignedUser)
            {
                if (NovologixSecurityContext.GetSecurityToken().OrganizationType == Shared.Payload.Library.OrganizationTypes.Internal)
                {
                    value = instance.ActiveActivity.AssignedUser.UserName;
                }
                else
                {
                    // Hide full assigned-to user id from external users.
                    if (!string.IsNullOrEmpty(instance.ActiveActivity.AssignedUser.UserName) && instance.ActiveActivity.AssignedUser.UserName.Contains('@'))
                    {
                        value = instance.ActiveActivity.AssignedUser.UserName.Split('@')[1];
                    }
                    else
                    {
                        value = string.Empty;
                    }
                }  
            }
            else
            {
                value = (string)instance.GetType().GetProperty(_propertyName).GetValue(instance, null);
            }
  
            label.Text = value;
        }
    }

And the usage of them when building the grid:

DropDownFilterTemplate planColumn = new DropDownFilterTemplate() { HeaderText = "Plan", DataField = "PlanName", SortExpression = "PlanName", ItemTemplate = new BasicTextColumnTemplate("PlanName") };
planColumn.FilterControlWidth = new Unit(140);
planColumn.HeaderStyle.Width = new Unit(140);
_grid.MasterTableView.Columns.Add(planColumn);

Hope that helps point you in the right direction.

Matt
0
Andrea
Top achievements
Rank 1
answered on 26 Jul 2011, 10:07 AM
I always get the same error.
Now I created a very simple example with radgrid created programmatically that use a filter custom column.
When I you try to filter you get always the message: Cannot create column with the specified type name: MyCustomFilteringColumn
I try some solution that I found in some threads, but no success.
Could you pls help me?
Default.aspx
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False"
    CellSpacing="0" GridLines="None" Skin="Telerik">
</telerik:RadGrid>

Deafult.cs
protected void Page_Load(object sender, EventArgs e) {
    if (!IsPostBack) {
        RadGrid1.NeedDataSource += grid_NeedDataSource;
        RadGrid1.MasterTableView.DataKeyNames = new[] {"Id"};
        RadGrid1.AllowFilteringByColumn = true;
        RadGrid1.MasterTableView.AllowFilteringByColumn = true;
 
        RadGrid1.MasterTableView.Columns.Clear();
 
        var checkColumn = new GridCheckBoxColumn();
        RadGrid1.MasterTableView.Columns.Add(checkColumn);
        checkColumn.DataType = typeof (bool);
        checkColumn.UniqueName = "CheckboxColumn";
        checkColumn.DataField = "CheckboxProp";
        checkColumn.HeaderText = "Checkbox Header";
        checkColumn.FilterListOptions = GridFilterListOptions.VaryByDataType;
 
        var newColumn = new GridBoundColumn();
        RadGrid1.MasterTableView.Columns.Add(newColumn);
        newColumn.DataType = typeof (string);
        newColumn.UniqueName = "StringColumn";
        newColumn.DataField = "StringProp";
        newColumn.HeaderText = "String Header";
        newColumn.FilterListOptions = GridFilterListOptions.VaryByDataType;
 
        var gridColumn = new MyCustomFilteringColumn();
        RadGrid1.MasterTableView.Columns.Add(gridColumn);
        gridColumn.ItemTemplate = new BasicTextColumnTemplate("MyFilteringProp");
        gridColumn.HeaderText = "MyFiltering Header";
    }
}
 
private void grid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e) {
    var myList = new List<MyItem>();
    for (int i = 1; i < 10; i++) {
        var myItem = new MyItem
                         {
                             Id = 1,
                             StringProp = "Text" + i,
                             CheckboxProp = true,
                             MyFilteringProp = "Item " + i
                         };
        myList.Add(myItem);
    }
    RadGrid1.DataSource = myList;
}
 
#region Nested type: MyItem
 
public class MyItem
{
    public int Id { get; set; }
 
    public string StringProp { get; set; }
 
    public bool CheckboxProp { get; set; }
 
    public string MyFilteringProp { get; set; }
}
 
#endregion

FilteringTemplateColumns.cs

public class MyCustomFilteringColumn : GridTemplateColumn
{
    protected override void SetupFilterControls(TableCell cell)
    {
        var rcBox = new RadComboBox
        {
            ID = "DropDownList1",
            AutoPostBack = true,
            DataTextField = DataField,
                            DataValueField = DataField
                        };
        rcBox.SelectedIndexChanged += rcBox_SelectedIndexChanged;
 
        rcBox.Items.Add(new RadComboBoxItem("", ""));
        for (int i = 1; i <= 10; ++i) {
            var item = new RadComboBoxItem("Item " + i, i.ToString());
            rcBox.Items.Add(item);
        }
        cell.Controls.Add(rcBox);
    }
 
    protected override void SetCurrentFilterValueToControl(TableCell cell) {
        if (!(CurrentFilterValue == "")) {
            ((RadComboBox) cell.Controls[0]).Items.FindItemByText(CurrentFilterValue).Selected = true;
        }
    }
 
    protected override string GetCurrentFilterValueFromControl(TableCell cell) {
        string currentValue = ((RadComboBox) cell.Controls[0]).SelectedItem.Value;
        CurrentFilterFunction = (currentValue != "") ? GridKnownFunction.EqualTo : GridKnownFunction.NoFilter;
        return currentValue;
    }
 
    private void rcBox_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e) {
        ((GridFilteringItem) (((RadComboBox) sender).Parent.Parent)).FireCommandEvent("Filter", new Pair());
    }
}

BasicTextColumnTemplate.cs

public class BasicTextColumnTemplate : ITemplate
{
    private readonly string propertyName;
    private Label label;
 
    public BasicTextColumnTemplate(string propertyName) {
        this.propertyName = propertyName;
    }
 
    #region ITemplate Members
 
    public void InstantiateIn(Control container) {
        label = new Label();
        label.DataBinding += label_DataBinding;
        container.Controls.Add(label);
    }
 
    #endregion
 
    private void label_DataBinding(object sender, EventArgs e) {
        var myLabel = (Label) sender;
        var container = (GridDataItem) myLabel.NamingContainer;
        object dataItem = container.DataItem;
        var value = (string) dataItem.GetType().GetProperty(propertyName).GetValue(dataItem, null);
        myLabel.Text = value;
    }
}




0
Andrea
Top achievements
Rank 1
answered on 26 Jul 2011, 12:36 PM
FInally I have solved! Thanks.
0
Ben
Top achievements
Rank 1
answered on 15 Dec 2011, 07:46 PM
Hi Andrea,

How did you resolve your problem? I have the same problem and would greatly appreciate any details you can share!

(did you end up setting enableviewstate=false? Or did you use Matt's example above?)

Thanks,
Ben
0
Nathan
Top achievements
Rank 2
answered on 04 Feb 2012, 11:20 PM
I'm also having problems with this. Could you please let me know what your solution was?

I'm attempting to set the ItemTemplate and FilterTemplate using custom class that inherits ITemplate, but I get the error message below on any ajax request (not just filtering).

Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '
<!DOCTYPE html PUB'  



My column configuration: The following works fine if I comment out the line that sets the FilterTemplate. Anyone have suggestions?
GridTemplateColumn myColumn = new GridTemplateColumn();
myColumn.UniqueName = "Workflow";
myColumn.HeaderText = "<nobr>Workflow</nobr>";
myColumn.AllowFiltering = true;
myColumn.FilterTemplate = new FilterTemplateForMultiSelectCombo("combo");
myColumn.ItemTemplate = new ColumnTemplateForDetail("lblWorkflow");
 
this.grdSummary.MasterTableView.Columns.Add(myColumn);
0
Maria Ilieva
Telerik team
answered on 08 Feb 2012, 11:09 AM
Hello Nathan,

I would suggest you to review the blog post below which elaborates on this error and provide possible solution:

http://blogs.telerik.com/hristodeshev/posts/07-06-24/firewalls-breaking-asp-net-ajax.aspx

Kind regards,
Maria Ilieva
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
0
Nathan
Top achievements
Rank 2
answered on 08 Feb 2012, 06:27 PM
My problem is being caused by the RadComboBox, when it's changed to a regular label control it works fine.

I'm creating a dynamic column and setting it's "FilterTemplate" using a class that inherits ITemplate, the class is "FilterTemplateForMultiSelectCombo". When I use a RadComboBox in "InstantiateIn" I get the error message on any ajax request that page does, not just from the combobox. If I change this control to something other than combo box, it works fine. Each test I'm only adding the control, nothing else. Please see each example below:

FilterTemplateForMultiSelectCombo with RadComboBox:
public void InstantiateIn(Control container)
{
    comboBox = new RadComboBox();
    comboBox.ID = "cmb" + Column.Code;
 
    container.Controls.Add(comboBox);
}

FilterTemplateForMultiSelectCombo with LABEL:  (Works)
public void InstantiateIn(Control container)
{
    lblLabel = new Label();
    lblLabel.ID = "lblTest" + Column.Code;
 
    container.Controls.Add(lblLabel);
}

Thanks!
0
asilioni
Top achievements
Rank 1
answered on 02 May 2012, 03:09 PM
Hello Maria,
a have created a web user control and added a radgrid control to it. At the radgrid, i want to have a combobox filter column, so i adde int the .ascx file the following line of code:

 

 

<% @ Register TagPrefix="custom" namespace="DixonsSalesPromotionToolWebApp" Assembly="DixonsSalesPromotionToolWebApp" %>

And i created the filter column like that:

<custom:MyCustomFilteringColumn DataField="Brandname" FilterControlWidth="180px" HeaderText="Κατασκευαστής">
                           <headerstyle width="25%" />
                               <itemtemplate>
                                   <%# Eval("Brandname") %>                                   
                               </itemtemplate>
                       </custom:MyCustomFilteringColumn>

The code for the class "MyCustomFilteringColumn" is placed in the .ascx.cs file of the user control. Everything works fine in visual studio, but i want to add this control to a sharepoint page. When i do so, i get the following error:
Could not load file or assembly 'DixonsSalesPromotionToolWebApp' or one of its dependencies. The system cannot find the file specified.

How can i get it work??

Thanks a lot for your time,
Angie

 

 

 

0
pooja
Top achievements
Rank 1
answered on 22 May 2012, 01:53 PM
Can any body tell me that how can i use Custom filtering on some columns and Grid default filtering on another i am working on that but always get filter expression blank.Plz reply if know the solution.
0
Iana Tsolova
Telerik team
answered on 25 May 2012, 04:11 PM
Hello pooja,

If to accomplish your custom filters you are working with the FilterExpression property, it might me hard to maintain the built-in filters as well. The best way to achieve your goal is to define FilterTemplate for the columns having custom filter and firing the built-in filter commands there. See the below sample:
http://demos.telerik.com/aspnet-ajax/grid/examples/programming/filtertemplate/defaultcs.aspx

Kind regards,
Iana Tsolova
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
Tags
Grid
Asked by
Matt
Top achievements
Rank 1
Answers by
Mira
Telerik team
Andrea
Top achievements
Rank 1
Matt
Top achievements
Rank 1
Ben
Top achievements
Rank 1
Nathan
Top achievements
Rank 2
Maria Ilieva
Telerik team
asilioni
Top achievements
Rank 1
pooja
Top achievements
Rank 1
Iana Tsolova
Telerik team
Share this question
or