Filter using combobox inside radgrid

29 posts, 2 answers
  1. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 10 Dec 2013 Link to this post

    I have gone through a couple of examples to achieve this. I am unable to bind my combobox to a datasource. The combobox on dropdown doesn't display a list of values.
    I have a RadGrid as follows:
    _RadGrid1.MasterTableView.DataKeyNames = new string[] { this._PopRuleList.PopCapabilityRuleIdColumn.ColumnName };             _RadGrid1.Width = Unit.Percentage(98);             _RadGrid1.PageSize = 15;             _RadGrid1.AllowPaging = true;             _RadGrid1.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;             _RadGrid1.AllowSorting = true;             _RadGrid1.AllowFilteringByColumn = _ShowFilter;             _RadGrid1.ShowStatusBar = _ShowFilter;             _RadGrid1.AutoGenerateColumns = false;             _RadGrid1.MasterTableView.NoMasterRecordsText = "There are no exceptions.";             _RadGrid1.Skin = "WebBlue";             _RadGrid1.MasterTableView.Width = Unit.Percentage(100);             _RadGrid1.ItemCommand += RadGrid1_ItemCommand;             _RadGrid1.ShowHeader = true;
    	
    	   string ColumnName = "Bandwidth";
                boundColumn = new GridBoundColumn();
                boundColumn.FilterTemplate = new MyTemplate(ColumnName, _RadGrid1);
                _RadGrid1.MasterTableView.Columns.Add(boundColumn);
                boundColumn.DataField = this._PopRuleList.BandwidthsColumn.ColumnName;
                boundColumn.AllowFiltering = true;
                boundColumn.HeaderText = "Bandwidth";
                boundColumn.UniqueName = "Bandwidth";
                boundColumn.HeaderStyle.Width = Unit.Pixel(25);
    
    
    Also I have the following class:
    class MyTemplate : ITemplate
    {
        protected RadComboBox combo;
        private string colname;
        RadGrid radgrid;
        GlobalCrossing.IFO.ServerControls.Pops.CapabilitiesExceptionListCtrl ce = new GlobalCrossing.IFO.ServerControls.Pops.CapabilitiesExceptionListCtrl();
     
        public MyTemplate(string cName, RadGrid grid)
        {
            colname = cName;
            radgrid = grid;
        }
        public void InstantiateIn(System.Web.UI.Control container)
        {
            combo = new RadComboBox();
            combo.ID = "RadComboBoxControl";
            combo.DataBinding += new EventHandler(RadComboBoxControl_DataBinding);
            container.Controls.Add(combo);
            combo.AutoPostBack = true;
            combo.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(RadComboBoxControl_SelectedIndexChanged);
        }
     
        public void RadComboBoxControl_DataBinding(object sender, EventArgs e)
        {
            RadComboBox combo = (RadComboBox)sender;
            GridFilteringItem container = (GridFilteringItem)combo.NamingContainer;
     
            combo.DataTextField = ce._PopRuleList.BandwidthsColumn.ColumnName;
            combo.DataValueField = ce._PopRuleList.BandwidthsColumn.ColumnName;
            combo.DefaultItem.Text = "All";
            combo.EnableAutomaticLoadOnDemand = true;
            combo.AllowCustomText = true;
            combo.DataSource = ce._PopRuleList;
        }
     
        void RadComboBoxControl_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            RadComboBox combo = sender as RadComboBox;
            string filterExpression;
            filterExpression = "([Bandwidth] LIKE '" + e.Value + "')";
            radgrid.MasterTableView.FilterExpression = filterExpression;
            radgrid.MasterTableView.Rebind();
        }
    }
    Please let me know how can I bind the RadComboBox so that it displays a list of values to select from.

  2. Nencho
    Admin
    Nencho avatar
    1864 posts

    Posted 13 Dec 2013 Link to this post

    Hello Ruchi,

    The reason for the not proper population with data of the RadComboBox is that the DataBinding event handler, where the control should be supplied with data, is probably never reached. I would suggest you to explicitly call the combo.DataBind(), in order to push the control to request its datasource.

    Regards,
    Nencho
    Telerik
    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 the blog feed now.
  3. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 10 Feb 2014 in reply to Nencho Link to this post

    I want all the columns in the RadGrid to have filtering option. It works when I implement it to one column. But when I try to do the same for another column it doesnt work.  This is what I am doing to add filtering to 2 columns:

               boundColumn = new GridBoundColumn();
                columnName = this._PopRuleList.BandwidthsColumn.ColumnName;            
                boundColumn.FilterTemplate = new MyTemplate(columnName, _RadGrid1);
                _RadGrid1.MasterTableView.Columns.Add(boundColumn);
                boundColumn.DataField = columnName;
                boundColumn.AllowFiltering = true;
                boundColumn.HeaderText = "Bandwidths";
                boundColumn.UniqueName = "Bandwidths";
                boundColumn.HeaderStyle.Width = Unit.Pixel(200);

                columnName = this._PopRuleList.PopCapabilityRuleIdColumn.ColumnName;
                boundColumn = new GridBoundColumn();
                boundColumn.FilterTemplate = new MyTemplate(columnName, _RadGrid1);
                _RadGrid1.MasterTableView.Columns.Add(boundColumn);
                boundColumn.DataField = columnName;
                boundColumn.HeaderText = "Exception ID";
                boundColumn.UniqueName = "PopRuleId";
                boundColumn.AllowFiltering = true;



  4. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 10 Feb 2014 Link to this post

    This is the error I get: Multiple controls with the same ID 'RadComboBox Control' were found. FindControl requires that controls have unique IDs.
    I found this as a solution: http://stackoverflow.com/questions/1663067/asp-net-server-control-based-on-radcombobox-postback-issue
    Please suggest a way out.
  5. Answer
    Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 11 Feb 2014 in reply to RB Link to this post

    Hi,

    You are receiving such an error because you are creating controls with the same ID. In your code to create FilterTemplate, I guess you have RadComboBox and you have ID set. Please set a UniqueID for each column Filter Template.
    You may try something like this:

    C#:
    ComboBox.ID = "ComboBox"+Guid.NewGuid().ToString("N");
     
    //or
     
    ComboBox.ID = "ComboBox"+columnName;

    Thanks,
    Shinu
  6. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 13 Feb 2014 in reply to Shinu Link to this post

    Thanks.It solved the problem. 
    I further noticed, that it does not filter for Integer.It filters for String but not for Integers.
    Here is my filterexpression:
     filterExpression = "([" + colname + "] LIKE '" + e.Value + "')";
  7. Princy
    Princy avatar
    17421 posts
    Member since:
    Mar 2007

    Posted 14 Feb 2014 in reply to RB Link to this post

    Hi,

    Please take a look into the following documentation, it discuss the various ways of writing FilterExpression for int and string.
    Operating with the FilterExpression of Telerik RadGrid Manually.

    Thanks,
    Princy

  8. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 05 Mar 2014 in reply to Princy Link to this post

    Thanks. Operating with the FilterExpression of Telerik RadGrid Manually helped me. In continuation with filtering, I have a GridCheckBoxColumn as follows:
    GridCheckBoxColumn cbColumn = new GridCheckBoxColumn();
               _RadGrid1.MasterTableView.Columns.Add(cbColumn);
               cbColumn.AllowSorting = true;
               cbColumn.UniqueName = "Active";
               cbColumn.FilterListOptions = GridFilterListOptions.VaryByDataType;
               cbColumn.CurrentFilterFunction = GridKnownFunction.EqualTo;
               cbColumn.CurrentFilterValue = "true";
               cbColumn.DataField = this._PopRuleList.IsActiveColumn.ColumnName;
               cbColumn.HeaderText = "Active";
               cbColumn.HeaderStyle.Width = Unit.Pixel(30);
    I want to check whether it is checked or not before filtering. Hence I added the following in RadComboBoxControl_SelectedIndexChanged:
    foreach (GridDataItem item in radgrid.MasterTableView.Items)
            {
                CheckBox chk = item["Active"].Controls[0] as CheckBox;
                if (chk.Checked)
                    isActive = true;
                else
                    isActive = false;
            }

    By default the checkbox is checked. Hence it works fine initially. When I uncheck it and filter, it again works fine with chk.Checked returning false. But if I check it again, it keeps returning false. Could you please help me.

  9. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 05 Mar 2014 in reply to RB Link to this post

    On careful observation, I found that foreach (GridDataItem item in radgrid.MasterTableView.Items) iterates through the MasterTableView. Hence if the table has 3 records, it iterates through the 3 records and since their isActive column is not checked it returns false. But on top of it resides the checkbox which I can either check or uncheck. I need this checkbox's value. If it is checked, all active records are displayed and if unchecked, all inactive records are displayed. I have attached a sample jpg for your reference.
  10. Princy
    Princy avatar
    17421 posts
    Member since:
    Mar 2007

    Posted 07 Mar 2014 in reply to RB Link to this post

    Hi,

    I guess you want to have the filter checkbox value. Please try the following code snippet.

    C#:
    protected void Page_Init(object source, System.EventArgs e)
    {
      RadGrid1.ItemDataBound += new GridItemEventHandler(RadGrid1_ItemDataBound);
    }
    void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
      if (e.Item is GridFilteringItem)
      {
        GridFilteringItem filter = (GridFilteringItem)e.Item;
        CheckBox chk = filter["Active"].Controls[0] as CheckBox;
        if (chk.Checked)
         isActive = true;
        else
         isActive = false;
      }
    }

    Thanks,
    Princy
  11. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 10 Mar 2014 in reply to Princy Link to this post

    Nope it did not work. Still fails to get the correct value.
    OnInit I am adding the checkbox as follows:
     The first time I want the checkbox to be checked.
       protected override void OnInit(EventArgs e)
            {
                 :
                 :
                 this._RadGrid1.ItemDataBound += new GridItemEventHandler(RadGrid1_ItemDataBound);
                 DefineGridStructure();
                 :
                 :
                base.OnInit(e);
                this.DataBind();
    }
     
     void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
            {
                if (e.Item is GridFilteringItem)
                {
                    GridFilteringItem filter = (GridFilteringItem)e.Item;
                    CheckBox chk = filter["Active"].Controls[0] as CheckBox;
                    if (chk.Checked)
                        isActive = true;
                    else
                        isActive = false;
                }
            }
     
     private void DefineGridStructure()
            {
                  :
                  :
                 boundColumn = new GridBoundColumn();
                _RadGrid1.MasterTableView.Columns.Add(boundColumn);
                boundColumn.DataField = this._PopRuleList.IsActiveColumn.ColumnName;
                boundColumn.AllowFiltering = true;
                boundColumn.HeaderText = "Active";
                boundColumn.UniqueName = "ActiveTextCol";
                boundColumn.HeaderStyle.Width = Unit.Pixel(25);
                boundColumn.Display = false;
     
                GridCheckBoxColumn cbColumn = new GridCheckBoxColumn();
                _RadGrid1.MasterTableView.Columns.Add(cbColumn);
                cbColumn.AllowSorting = true;
                cbColumn.UniqueName = "Active";
                cbColumn.FilterListOptions = GridFilterListOptions.VaryByDataType;
                cbColumn.CurrentFilterFunction = GridKnownFunction.EqualTo;
                cbColumn.CurrentFilterValue = "true";
                cbColumn.DataField = this._PopRuleList.IsActiveColumn.ColumnName;
                cbColumn.HeaderText = "Active";
                cbColumn.HeaderStyle.Width = Unit.Pixel(30);
                    :
                    :
    }
  12. Princy
    Princy avatar
    17421 posts
    Member since:
    Mar 2007

    Posted 10 Mar 2014 in reply to RB Link to this post

    Hi,

    I was not able to replicate the issue. Here is the full code snippet that I tried.

    ASPX:
    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
     
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind_newConnectionString3 %>"
        SelectCommand="SELECT  * FROM [Orders]"></asp:SqlDataSource>

    C#:
    bool isActive;
    protected override void OnInit(EventArgs e)
    {  
        DefineGridStructure();
        base.OnInit(e);     
    }
       
    void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridFilteringItem)
        {
            GridFilteringItem filter = (GridFilteringItem)e.Item;
            CheckBox chk = filter["IsTrue"].Controls[0] as CheckBox;
            if (chk.Checked)
                isActive = true;
            else
                isActive = false;
        }
    }
     
    private void DefineGridStructure()
    {
        RadGrid grid = new RadGrid();
        grid.ID = "RadGrid1";
        grid.DataSourceID = "SqlDataSource1";
        grid.PageSize = 15;
        grid.AllowPaging = true;
        grid.AutoGenerateColumns = false;
        grid.AllowFilteringByColumn = true;
        grid.ItemDataBound += new GridItemEventHandler(RadGrid1_ItemDataBound);
     
        GridBoundColumn boundColumn = new GridBoundColumn();
        boundColumn.DataField = "OrderID";
        boundColumn.AllowFiltering = true;
        boundColumn.HeaderText = "OrderID";
        boundColumn.UniqueName = "OrderID";
        grid.MasterTableView.Columns.Add(boundColumn);
     
        GridCheckBoxColumn cbColumn = new GridCheckBoxColumn();
        cbColumn.AllowSorting = true;
        cbColumn.UniqueName = "IsTrue";
        cbColumn.FilterListOptions = GridFilterListOptions.VaryByDataType;
        cbColumn.CurrentFilterFunction = GridKnownFunction.EqualTo;
        cbColumn.CurrentFilterValue = "true";
        cbColumn.DataField = "IsTrue";
        cbColumn.HeaderText = "IsTrue";
        grid.MasterTableView.Columns.Add(cbColumn);
     
        this.PlaceHolder1.Controls.Add(grid);
    }

    Thanks,
    Princy
  13. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 11 Mar 2014 in reply to Princy Link to this post

    Nope. Still doesn't work for me! Here is the entire code:
        public class CapabilitiesExceptionListCtrl : WebControl
        {
            #region Members
     
            private UpdatePanel _UpdatePanel = new UpdatePanel();      
            private PopCapabilityRuleTable _PopRuleList = new PopCapabilityRuleTable();
            Telerik.Web.UI.RadGrid _RadGrid1 = new Telerik.Web.UI.RadGrid();
            protected ImageButton ImgDoc1, ImgXls1, ImgPdf1;
            private string _DocumentId = string.Empty;
            private int _PopId = 0;
            private string _ErrorMessage = string.Empty;
            private bool _IsReadOnly;
            private bool _ShowDelete = true;
            private bool _IsError = false;
            private bool _ShowFilter = true;
            private string _ExportType = string.Empty;
            private string _Title = string.Empty;
            private bool isActive;
            #endregion
     
            #region Constructors
     
            public CapabilitiesExceptionListCtrl()
                : base()
            {
                
                this.ControlStyle.Width = System.Web.UI.WebControls.Unit.Percentage(100);
            }
     
            public CapabilitiesExceptionListCtrl(int popId)
                : this() { _PopId = popId; }
     
            #endregion
     
            #region Properties
     
            public bool IsReadOnly { get { return _IsReadOnly; } set { _IsReadOnly = value; } }
            public bool ShowDelete { get { return _ShowDelete; } set { _ShowDelete = value; } }
            public bool HasRows { get { return (_RadGrid1.MasterTableView.Items.Count > 0); } }
            public bool ShowFilter { get { return _ShowFilter; } set { _ShowFilter = value; _RadGrid1.AllowFilteringByColumn = _ShowFilter; } }
            public int PopId { get { return _PopId; } set { _PopId = value; } }
            public string Title { get { return _Title; } set { _Title = value; } }
     
            #endregion
     
            #region Overrides
     
            protected override void OnInit(EventArgs e)
            {         
                this.Controls.Clear();    
                
                DefineGridStructure();
     
                var updatePanel = new UpdatePanel();
                updatePanel.ID = "ajaxPanel";
                updatePanel.UpdateMode = UpdatePanelUpdateMode.Always;
                updatePanel.ContentTemplateContainer.Controls.Add(this._RadGrid1);
                this.Controls.Add(updatePanel);
     
                base.OnInit(e);
     
                this.DataBind();
            }
     
            protected override void OnPreRender(EventArgs e)
            {
                _RadGrid1.MasterTableView.Rebind();
                if (!this.HasRows && !_ShowFilter)
                {
                    _RadGrid1.ShowHeader = false;            
                }
                base.OnPreRender(e);
            }
     
            protected override void Render(System.Web.UI.HtmlTextWriter writer)
            {
                base.Render(writer);
     
                if (this._IsError)
                {
                    this.Controls.AddAt(0, new System.Web.UI.LiteralControl(string.Format(" <A class=\"GXInputErrorIMG\" href=\"#\">{0}</A>", this._ErrorMessage)));
                }
            }
     
            #endregion
     
            #region Private Methods
     
     
            private void LoadPopList()
            {    
                        _PopRuleList = new PopCapabilityRule_List().ExecuteTypedDataTable();         
            }
     
            #endregion
     
            #region Events
     
            void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
            {
                GridDataItem dataItem = null;
                int ruleId = 0;
                if (e.CommandName == "DeletePopRule")
                {
                    if (e.Item is GridDataItem)
                    {
                        try
                        {
                            dataItem = e.Item as GridDataItem;
                            ruleId = int.Parse(dataItem["PopRuleId"].Text);
     
                            bool deleted = (new PopCapabilityRule_Delete().ExecuteNonQuery(ruleId)) > 0;
                        }
                        catch (Exception exception)
                        {
                            this._IsError = true;
                            this._ErrorMessage = exception.Message;                      
                        }
                        this.Refresh();
                    }
                }
            }
     
            void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
            {
                if (e.Item is GridFilteringItem)
                {
                    GridFilteringItem filter = (GridFilteringItem)e.Item;
                    CheckBox chk = filter["Active"].Controls[0] as CheckBox;
                    if (chk.Checked)
                        isActive = true;
                    else
                        isActive = false;
                }
            }
            #endregion
     
            #region Private Methods
            public void Refresh()
            {
                this.OnInit(System.EventArgs.Empty);
            }
     
            private void DefineGridStructure()
            {
                _RadGrid1.MasterTableView.DataKeyNames = new string[] { this._PopRuleList.PopCapabilityRuleIdColumn.ColumnName };
                _RadGrid1.Width = Unit.Percentage(98);
                _RadGrid1.PageSize = 15;
                _RadGrid1.AllowPaging = true;
                _RadGrid1.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
                _RadGrid1.AllowSorting = true;
                _RadGrid1.AllowFilteringByColumn = _ShowFilter;
                _RadGrid1.ShowStatusBar = _ShowFilter;
                _RadGrid1.AutoGenerateColumns = false;
                _RadGrid1.MasterTableView.NoMasterRecordsText = "There are no exceptions.";
                _RadGrid1.Skin = "WebBlue";
                _RadGrid1.MasterTableView.Width = Unit.Percentage(100);
                _RadGrid1.ItemCommand += RadGrid1_ItemCommand;
                _RadGrid1.ItemDataBound += new GridItemEventHandler(RadGrid1_ItemDataBound);
                _RadGrid1.ShowHeader = true;
                LoadPopList();
     
                GridBoundColumn boundColumn;
                string columnName;
                columnName = this._PopRuleList.PopCapabilityRuleIdColumn.ColumnName;
                boundColumn = new GridBoundColumn();
     
                boundColumn.FilterTemplate = new CapabilitiesExceptionListCtrlTemplate(columnName, _RadGrid1, this._PopRuleList.SelectDistinct(columnName), isActive);
                _RadGrid1.MasterTableView.Columns.Add(boundColumn);
                boundColumn.DataField = columnName;
                boundColumn.HeaderText = "Exception ID";
                boundColumn.UniqueName = "PopCapabilityRuleId";
                boundColumn.AllowFiltering = true;
     
                boundColumn = new GridBoundColumn();
                _RadGrid1.MasterTableView.Columns.Add(boundColumn);
                boundColumn.DataField = this._PopRuleList.IsActiveColumn.ColumnName;
                boundColumn.AllowFiltering = true;
                boundColumn.HeaderText = "Active";
                boundColumn.UniqueName = "ActiveTextCol";
                boundColumn.HeaderStyle.Width = Unit.Pixel(25);
                boundColumn.Display = false;
     
                GridCheckBoxColumn cbColumn = new GridCheckBoxColumn();
                _RadGrid1.MasterTableView.Columns.Add(cbColumn);
                cbColumn.AllowSorting = true;
                cbColumn.UniqueName = "Active";
                cbColumn.FilterListOptions = GridFilterListOptions.VaryByDataType;
                cbColumn.CurrentFilterFunction = GridKnownFunction.EqualTo;
                cbColumn.CurrentFilterValue = "true";
                cbColumn.DataField = this._PopRuleList.IsActiveColumn.ColumnName;
                cbColumn.HeaderText = "Active";
                cbColumn.HeaderStyle.Width = Unit.Pixel(30);
     
                boundColumn = new GridBoundColumn();
                columnName = this._PopRuleList.CreateIdColumn.ColumnName;
                boundColumn.FilterTemplate = new CapabilitiesExceptionListCtrlTemplate(columnName, _RadGrid1, this._PopRuleList.SelectDistinct(columnName), isActive);
                _RadGrid1.MasterTableView.Columns.Add(boundColumn);
                boundColumn.DataField = columnName;
                boundColumn.AllowFiltering = true;
                boundColumn.HeaderText = "Created By";
                boundColumn.UniqueName = "CreatedBy";
                boundColumn.HeaderStyle.Width = Unit.Pixel(80);
     
                if (this._ShowDelete)
                {
                    GridButtonColumn buttonColumn = new GridButtonColumn();
                    _RadGrid1.MasterTableView.Columns.Add(buttonColumn);
                    buttonColumn.DataTextField = this._PopRuleList.PopCapabilityRuleIdColumn.ColumnName;
                    buttonColumn.HeaderText = "Delete";
                    buttonColumn.UniqueName = "DeleteColumn";
                    buttonColumn.ButtonType = GridButtonColumnType.ImageButton;
                    buttonColumn.ImageUrl = this.ResolveUrl("/ucommand/CRM/images/") + "Delete.gif";
                    buttonColumn.ConfirmText = "Delete Pop Rule Exception?";
                    buttonColumn.CommandName = "DeletePopRule";
                    buttonColumn.CommandArgument = this._PopRuleList.PopCapabilityRuleIdColumn.ColumnName;
                    buttonColumn.HeaderStyle.Width = Unit.Pixel(50);
                }
                _RadGrid1.EnableLinqExpressions = false; //required for the expression to be recognized
                _RadGrid1.MasterTableView.FilterExpression = "([IsActive] = 'true')";
                _RadGrid1.DataSource = _PopRuleList;
            }
     
            void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
            {
                LoadPopList();
                _RadGrid1.DataSource = _PopRuleList;
            }         
            #endregion
        }
     
     
    class CapabilitiesExceptionListCtrlTemplate : ITemplate
    {
        protected RadComboBox combo;
        private string colname;
        RadGrid radgrid;
        String selectedValue;
        DataTable distinctPopRuleList;
        bool isActiveValue;
        public CapabilitiesExceptionListCtrlTemplate(string cName, RadGrid grid, DataTable DisctinctPopRuleList, bool isActive)
        {
            colname = cName;
            radgrid = grid;
            distinctPopRuleList = DisctinctPopRuleList;
            isActiveValue = isActive;
        }
        public void InstantiateIn(System.Web.UI.Control container)
        {
            combo = new RadComboBox();
            combo.ID = "RadComboBoxControl" + colname;
            combo.DataBinding += new EventHandler(RadComboBoxControl_DataBinding);
            container.Controls.Add(combo);
            combo.AutoPostBack = true;
            combo.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(RadComboBoxControl_SelectedIndexChanged);
        }
     
        public void RadComboBoxControl_DataBinding(object sender, EventArgs e)
        {
            RadComboBox combo = (RadComboBox)sender;
            GridFilteringItem container = (GridFilteringItem)combo.NamingContainer;
     
            combo.DataTextField = colname;
            combo.DataValueField = colname;
            combo.EnableAutomaticLoadOnDemand = true;
            combo.AllowCustomText = true;
            combo.AppendDataBoundItems = true;
            combo.DataSource = distinctPopRuleList;
            combo.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem { Text = "All", Value = "All" });
            combo.SelectedValue = selectedValue;
        }
     
        void RadComboBoxControl_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string filterExpression;
            //int
            if (colname.Equals("PopCapabilityRuleId"))
                filterExpression = "([" + colname + "] =" + e.Value + ")";
            //String
            else
                filterExpression = "([" + colname + "] ='" + e.Value + "')";
            filterExpression += " AND ([IsActive] =' " + isActiveValue + "')";
            if (e.Value.Equals("All"))
                filterExpression = "([IsActive] = ' " + isActiveValue + "')";
     
            radgrid.MasterTableView.FilterExpression = filterExpression;
            selectedValue = e.Value;
            radgrid.MasterTableView.Rebind();
        }
    }
  14. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 11 Mar 2014 in reply to RB Link to this post

    I want to pass the value of isActive to the template so that while filtering it should know whether isActive is true or false and filter accordingly.
  15. Princy
    Princy avatar
    17421 posts
    Member since:
    Mar 2007

    Posted 12 Mar 2014 in reply to RB Link to this post

    Hi,

    You can set the AutoPostBackOnFilter of the CheckBox column to true. Please take a look at the sample code snippet, you may try something similar.

    C#:
    RadGrid grid;
    static bool isActive;
     
    protected void Page_Init(object sender, EventArgs e)
    {
        grid = new RadGrid();
        grid.AutoGenerateColumns = false;
        grid.AllowFilteringByColumn = true;     
        grid.EnableLinqExpressions = false;
        grid.NeedDataSource += new GridNeedDataSourceEventHandler(grid_NeedDataSource);
        grid.ItemDataBound += new GridItemEventHandler(grid_ItemDataBound);       
     
        string columnName = "ShipCity";
        GridBoundColumn boundColumn = new GridBoundColumn();
        boundColumn.FilterTemplate = new filterTemplate(columnName, grid, isActive);
        boundColumn.DataField = columnName;
        boundColumn.HeaderText = columnName;
        boundColumn.UniqueName = columnName;
        grid.MasterTableView.Columns.Add(boundColumn);
     
        GridCheckBoxColumn cbColumn = new GridCheckBoxColumn();
        cbColumn.AllowSorting = true;
        cbColumn.UniqueName = "IsTrue";
        cbColumn.AutoPostBackOnFilter = true;
        cbColumn.FilterListOptions = GridFilterListOptions.VaryByDataType;
        cbColumn.CurrentFilterFunction = GridKnownFunction.EqualTo;
        cbColumn.CurrentFilterValue = "true";
        cbColumn.DataField = "IsTrue";
        cbColumn.HeaderText = "IsTrue";     
        grid.MasterTableView.Columns.Add(cbColumn);
     
        PlaceHolder1.Controls.Add(grid);
    }
     
    void grid_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridFilteringItem)
        {
            GridFilteringItem filter = (GridFilteringItem)e.Item;
            CheckBox chk = filter["IsTrue"].Controls[0] as CheckBox;
            if (chk.Checked)
                isActive = true;
            else
                isActive = false;
        }
    }
     
    void grid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        grid.DataSource = GetDataTable("SELECT  * FROM Orders");
    }
     
    private class filterTemplate : ITemplate
    {
        protected RadComboBox combo;
        private string name;
        RadGrid radgrid;
        String selectedValue;
        bool isActiveValue;
        DataTable dt;
     
        public filterTemplate(string cName, RadGrid grid, bool isActive)
        {
            name = cName;
            radgrid = grid;
            isActiveValue = isActive;
        }
        public void InstantiateIn(System.Web.UI.Control container)
        {
            combo = new RadComboBox();
            combo.ID = "RadComboBoxControl" + name;
            combo.DataBinding += new EventHandler(RadComboBoxControl_DataBinding);
            container.Controls.Add(combo);
            combo.AutoPostBack = true;
            combo.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(RadComboBoxControl_SelectedIndexChanged);
        }
     
        public void RadComboBoxControl_DataBinding(object sender, EventArgs e)
        {
            RadComboBox combo = (RadComboBox)sender;
            GridFilteringItem container = (GridFilteringItem)combo.NamingContainer;
     
            combo.DataTextField = name;
            combo.DataValueField = name;
            combo.SelectedValue = radgrid.MasterTableView.GetColumn(name).CurrentFilterValue;
            combo.EnableAutomaticLoadOnDemand = true;
            combo.AllowCustomText = true;
            combo.AppendDataBoundItems = true;
            combo.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem { Text = "All", Value = "All" });
            try
            {
                dt = GetDataTable("SELECT distinct ShipCity FROM Orders");
                combo.DataSource = dt;
            }
            catch (Exception exception)
            {
            }
     
            combo.DataBind();
        }
     
        void RadComboBoxControl_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string filterExpression;
     
            filterExpression = "([" + name + "] ='" + e.Value + "')";
            filterExpression += " AND ([IsTrue] =' " + isActiveValue + "')";
            if (e.Value.Equals("All"))
                filterExpression = "([IsTrue] = ' " + isActiveValue + "')";
     
            radgrid.MasterTableView.FilterExpression = filterExpression;
            selectedValue = e.Value;
            radgrid.MasterTableView.Rebind();
        }
    }
     
    public static DataTable GetDataTable(string query)
    {
        String ConnString = ConfigurationManager.ConnectionStrings["Northwind_newConnectionString3"].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;
    }

    Thanks,
    Princy
  16. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 13 Mar 2014 in reply to Princy Link to this post

    Nope the issue is not resolved. The reason being that the call to  RadGrid1_ItemDataBound() is made after the template call. When the template is called, I send the isActive value, which in this case sends the default value. After this the RadGrid1_ItemDataBound()  is called. Hence template never gets the correct value.
  17. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 13 Mar 2014 Link to this post

    The other problem I am facing is, there are 2 stored procs SP1 and SP2. The RadGrid is bound to SP1 and the dropdown to SP2. ( The reason being SP1 doesnot have all the possible values of column "Name" and I want the dropdown to display all the possible values of column "Name". Hence, I bind it to SP2.) But the column "Name" in SP1 is defined as "Description" in SP2. Both the columns are named differently. I have done this with same column name in both stored procedures and it works good. But in this scenarion, it returns no record! Could you please guide me in this scenario.
  18. Viktor Tachev
    Admin
    Viktor Tachev avatar
    2469 posts

    Posted 18 Mar 2014 Link to this post

    Hello,

    For your convenience I have prepared a sample project where the described functionality is implemented. It seems to be working as expected on my end. Please give it a try and let me know if it is working for you as well.

    Regards,
    Viktor Tachev
    Telerik
     

    DevCraft Q1'14 is here! Watch the online conference to see how this release solves your top-5 .NET challenges. Watch on demand now.

     
  19. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 01 Apr 2014 in reply to Shinu Link to this post

    Shinu,
    you suggested that I use 
    ComboBox.ID = "ComboBox"+Guid.NewGuid().ToString("N");
      
    //or
      
    ComboBox.ID = "ComboBox"+columnName;

    I am using ComboBox.ID = "ComboBox"+columnName; to generate IDs. But  now in the grid I have 2 dropdowns which bind to the same database column. Dropdown A and AZ both bind to column A of the DB. 
    Hence a unique ID is not generated. I tries appending the ID with a random number but even that didnot work. 
    Can you please suggest a workaround?
  20. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 02 Apr 2014 in reply to RB Link to this post

    Hi,

    I'm not clear about your requirement. You can pass another string value to the ITemplate class to identify which dropdown you want to create. You may try something like shown below:

    C#:
    boundColumn.FilterTemplate = new ComboTemplate(grid, columnname, "dropdownA");
    boundColumn.FilterTemplate = new ComboTemplate(grid, columnname, "dropdownAZ");
     
    . . . .
     
    public class ComboTemplate : ITemplate
    {
        private RadGrid grid;
        private RadComboBox combo;
        private string columnName;
        private string dropdown;
      
        public ComboFilterTemplate(RadGrid radgrid, string ColumnName, string dropdownID)
        {
            grid = radgrid;
            dropdown= dropdownID;
            columnName = ColumnName;      
        }
        public void InstantiateIn(Control container)
        {
             combo = new RadComboBox();
             combo.ID = "ComboBox" + columnName + dropdown;
        }
    }

    Thanks,
    Shinu
  21. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 02 Apr 2014 in reply to Shinu Link to this post

    Hi,

    In my previous post the function name was mistyped. Its as follows:

    C#:
    public ComboTemplate(RadGrid radgrid, string ColumnName, string dropdownID)
      {
      }

    Thanks,
    Shinu
  22. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 03 Apr 2014 in reply to Shinu Link to this post

    Thanks. But how do I say which column needs to be filtered?
    void RadComboBoxControl_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
           {
               string filterExpression;
              
               filterExpression = "([" + colname + "] ='" + e.Value + "')";
               if (e.Value.Equals("All"))
                   filterExpression = " ";
              // filterExpression += " AND ([IsActive] =' " + isActiveValue + "')";
               radgrid.MasterTableView.FilterExpression = filterExpression;
               selectedValue = e.Value;
               radgrid.MasterTableView.Rebind();
           }

    When I select a value on AZ, the columns in A are filtered! Because the columnNames in both is same.
  23. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 04 Apr 2014 in reply to RB Link to this post

    Hi,

    You requirement is not clear to me. Could you provide your full code snippet. If you want to identify between two columns, you can try passing its UniqueName. Every column should have a UniqueName, hence using that we may identify the columns being filtered.

    Thanks,
    Shinu
  24. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 10 Apr 2014 Link to this post

    I have 5 columns in my radgrid. OUt of these, 2 columns are CityA and CityB. The dropdown of both these is populated from column CIty of Stored Proc ListOfCities. Because the dropdown of both these should have all the possible city values. But the rest of columns are bound to other StoredProc XYZ.
    Hence, both columns CityA and CityB have :
      boundColumn.FilterTemplate = new DropdownTemplate("City", this._RadGrid1, this._CityTypeTable, "CityA");
      boundColumn.FilterTemplate = new DropdownTemplate("City", this._RadGrid1, this._CityTypeTable, "CityB");

    The dropdownTemplate constructor is:
    public DropdownTemplate(string cName, RadGrid grid, DataTable DisctinctPopRuleList, string DropdownID)
          {
              colname = cName;
              radgrid = grid;
              distinctPopRuleList = DisctinctPopRuleList;
              dropdownId = DropdownID;
          }

    The first argument in the constructor cName is the column name of the  StoredProc. Hence both of them have same cName.
    Now, in SelectedIndexChanged, the filter expression for both of them is same since colName is same. Hence When a value from CityA dropdown is selected, CityA rows are filtered but when a value from CityB dropdown is selected, again CityA rows are filtered! Not CItyB. 
    void RadComboBoxControl_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
            {
                string filterExpression;
                filterExpression = "([" + colname + "] ='" + e.Value + "')";
                if (e.Value.Equals("All"))
                    filterExpression = " ";
               // filterExpression += " AND ([IsActive] =' " + isActiveValue + "')";
                radgrid.MasterTableView.FilterExpression = filterExpression;
                selectedValue = e.Value;
                radgrid.MasterTableView.Rebind();
            }

    How can i say in SelectedIndexChanged which column needs to be filtered?
  25. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 11 Apr 2014 in reply to RB Link to this post

    Hi,

    Please take a look at the below code snippet. I was able to get the correct column filtered.

    C#:
    RadGrid grid;
    protected void Page_Init(object sender, EventArgs e)
    {       
        grid = new RadGrid();
        grid.ID = "RadGrid1";
        . . . . . . . .
        string columnname = "Country";
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Country";
        boundColumn.HeaderText = "Country1";
        boundColumn.UniqueName = "Country1";       
        boundColumn.FilterTemplate = new ComboFilterTemplate(grid, columnname,"Country1");
        grid.MasterTableView.Columns.Add(boundColumn);
     
        columnname = "Country";
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Country";
        boundColumn.HeaderText = "Country2";
        boundColumn.UniqueName = "Country2";
        boundColumn.FilterTemplate = new ComboFilterTemplate(grid, columnname,"Country2");
        grid.MasterTableView.Columns.Add(boundColumn);
        
    }  
     
    public class ComboFilterTemplate : ITemplate
    {
    private RadGrid grid;
    private RadComboBox combo;
    private string columnName;
    private string uniqueName;  
     
    public ComboFilterTemplate(RadGrid radgrid, string ColumnName,string uniquename)
    {
        grid = radgrid;      
        columnName = ColumnName;
        uniqueName = uniquename;   
    }
    public void InstantiateIn(Control container)
    {    
        combo = new RadComboBox();
        combo.ID = "ComboBox" + uniqueName;
        container.Controls.Add(combo);
        combo.AutoPostBack = true;
        combo.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(combo_SelectedIndexChanged);
        combo.DataBinding += new EventHandler(combo_DataBinding);     
    }
     
    void combo_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox combo = sender as RadComboBox;     
        GridItem container = (GridItem)combo.NamingContainer;
        string filterExpression;
        filterExpression = "([" + columnName + "] ='" + e.Value + "')";
        if (e.Value.Equals("All"))
        {
            foreach (GridColumn column in grid.MasterTableView.OwnerGrid.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            grid.MasterTableView.FilterExpression = string.Empty;         
        }
        else
            grid.MasterTableView.FilterExpression = filterExpression;
            grid.MasterTableView.GetColumn(uniqueName).ItemStyle.ForeColor = Color.Red;//Test to identify which column is filtered
            grid.MasterTableView.Rebind();         
    }
     
    void combo_DataBinding(object sender, EventArgs e)
    {
        //Bind values to RadComboBox       

    Thanks,
    Shinu
  26. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 11 Apr 2014 in reply to Shinu Link to this post

    The column to be filtered does turn red, but still the other column gets filtered!

    void RadComboBoxControl_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
            {
                RadComboBox combo = sender as RadComboBox;
                GridItem container = (GridItem)combo.NamingContainer;
                string filterExpression;
                filterExpression = "([" + colname + "] ='" + e.Value + "')";
                radgrid.MasterTableView.FilterExpression = filterExpression;

                radgrid.MasterTableView.GetColumn(uniqueName).ItemStyle.ForeColor = System.Drawing.Color.Red;//Test to identify which column is filtered
                selectedValue = e.Value;
                radgrid.MasterTableView.Rebind();                    
            }
  27. Viktor Tachev
    Admin
    Viktor Tachev avatar
    2469 posts

    Posted 15 Apr 2014 Link to this post

    Hello Ruchi,

    Please note that the colname variable used in the filter expression needs to be different for the two columns.

    For example the colname for the first column would be "cityA" and for the second column - "cityB". This way when the filter expression is created the correct column would be filtered.


    Regards,
    Viktor Tachev
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  28. RB
    RB avatar
    126 posts
    Member since:
    Dec 2013

    Posted 15 Apr 2014 in reply to Viktor Tachev Link to this post

    That is exactly the problem here!. Both the columns have the same column name since they are both bound to the same database column! 
  29. Answer
    Viktor Tachev
    Admin
    Viktor Tachev avatar
    2469 posts

    Posted 17 Apr 2014 Link to this post

    Hi,

    When two columns in RadGrid are bound to the same data field the data in them is populated from the same source. This means that when the data in one of the columns is filtered the same result will be shown in both. This is an expected behavior.

    If you would like to have different data in the columns you would need to bind them to different fields in the data source.

    Regards,
    Viktor Tachev
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
Back to Top