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

RadGrid Custom Filter - DropDownList

14 Answers 699 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Mike
Top achievements
Rank 1
Mike asked on 10 Oct 2012, 04:32 PM
I am trying to implement a custom filter using the DropDownList control as documented in
http://www.telerik.com/help/aspnet-ajax/grid-filtering-with-dropdownlist.html

However, I am generating the RadGrid columns at runtime in the Page_Load event.

I receive the error "Exception of type 'System.Web.HttpUnhandledException' was thrown. when I try to filter the data. The grid and data load correctly. I receive the error only when I try to filter the data. The exception is trapped in the GLobal.asax. I cannot determine what is throwing the exception.

The RadGrid filtering works fine if I do not use the MyCustomFilteringColumn and simply use the GridBoundColumn for all columns that are created.

The project uses the Adventure Works 2008R2 database. I am displaying all records from the DimCustomer table. The "FirstName" column implements the custom control  "MyCustomFilteringColumn : GridBoundColumn". All other columns are "GridBoundColumn".

I'm not sure what I'm missing. Any help would be greatly appreciated.

Thanks,
Mike

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewMemberDetails.aspx.cs" Inherits="BillingPortal.ViewMemberDetails" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
    <title></title>
    <link href="Styles/VisualIdentity.css" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
    function PopupClose(button)
    {
        window.close();
    }
</script>
<body>
    <form id="form1" runat="server">
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
                <Scripts>
                    <%--Needed for JavaScript IntelliSense in VS2010--%>
                    <%--For VS2008 replace RadScriptManager with ScriptManager--%>
                    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
                    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
                    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
                </Scripts>
            </telerik:RadScriptManager>
    <div>
   <center> <h1><font color="#00458a"> Test RadGrid Custom Filter </font></h1>
     <telerik:RadGrid ID="RadGrid1" OnNeedDataSource="RadGrid2_NeedDataSource"
                     AllowPaging="True" runat="server" GridLines="None"  Width="1199px"
                      CellSpacing="0" AllowFilteringByColumn="True"
                     AutoGenerateColumns="False" Skin="Windows7" >
    <MasterTableView Width="99%" CommandItemDisplay="Top" >
    <CommandItemSettings ShowAddNewRecordButton="false" ShowExportToExcelButton="false" ShowExportToWordButton="false" ShowExportToCsvButton="false" />
    <Columns>
    </Columns>
    </MasterTableView>
   </telerik:RadGrid>
   <h3 />
   <h3><asp:Label ID="lblError" runat="server" ForeColor="Red" Visible="False"></asp:Label>
   </h3>
   <h3 />
   <telerik:RadButton ID="btnClose" runat="server" OnClientClicked="PopupClose" Text="Close"></telerik:RadButton>
   </center>
    </div>
    </form>
</body>
</html>
 
 
 
 
 
 
 
 
    public partial class ViewMemberDetails : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblError.Visible = false;
 
            if (!IsPostBack)
            {
                DataTable dt;
 
                dt = GetData();
 
                // build RadGrid columns
 
                RadGrid1.MasterTableView.Columns.Clear();
 
                foreach (DataColumn dataColumn in dt.Columns)
                {
                    if (dataColumn.ColumnName == "FirstName")
                    {
                        MyCustomFilteringColumn gridColumn = new MyCustomFilteringColumn();
                        RadGrid1.MasterTableView.Columns.Add(gridColumn);
 
                        gridColumn.DataField = dataColumn.ColumnName;
                        gridColumn.HeaderText = dataColumn.ColumnName;
                        gridColumn.UniqueName = dataColumn.ColumnName;
                    }
                    else
                    {
                        GridBoundColumn boundColumn = new GridBoundColumn();
                        RadGrid1.MasterTableView.Columns.Add(boundColumn);
 
                        boundColumn.DataField = dataColumn.ColumnName;
                        boundColumn.HeaderText = dataColumn.ColumnName;
                        boundColumn.UniqueName = dataColumn.ColumnName;
                    }
                }
            }
        }
 
        protected void RadGrid2_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = GetData();
        }
 
        public DataTable GetData()
        {
            string sConnectionString;
 
            sConnectionString = "Server=.;Database=AdventureWorksDW2008R2;Trusted_Connection=Yes;";
 
            SqlConnection conn = new SqlConnection(sConnectionString);
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataSet dsSummary = new DataSet();
            DataTable dtSummary;
 
            try
            {
                conn.Open();
                cmd = new SqlCommand("SELECT * FROM [AdventureWorksDW2008R2].[dbo].[DimCustomer]", conn);
                cmd.CommandType = CommandType.Text;
                adapter.SelectCommand = cmd;
                adapter.Fill(dsSummary);
            }
            catch (Exception ex)
            {
                this.lblError.Visible = true;
                this.lblError.Text = ex.Message;
 
            }
            finally
            {
                conn.Close();
            }
 
            dtSummary = dsSummary.Tables[0];
 
            return dtSummary;
        }
 
        public class MyCustomFilteringColumn : GridBoundColumn
        {
            private object listDataSource = null;
            //RadGrid calls 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);
                DropDownList list = new DropDownList();
                list.ID = "list" + this.DataField;
                list.AutoPostBack = true;
                list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
                cell.Controls.AddAt(0, list);
                cell.Controls.RemoveAt(1);
                list.DataTextField = this.DataField;
                list.DataValueField = this.DataField;
 
                //list.DataSource = this.ListDataSource;
                list.DataSource = this.ListDataSource2;
 
                //string[] s1 = new string[3] { "John", "Paul", "Mary" };
                //ListDataSource = s1;
            }
            void list_SelectedIndexChanged(object sender, EventArgs e)
            {
                GridFilteringItem filterItem = (sender as DropDownList).NamingContainer as GridFilteringItem;
                if (this.DataType == System.Type.GetType("System.Int32") || this.DataType == System.Type.GetType("System.Int16") || this.DataType == System.Type.GetType("System.Int64"))
                {
                    filterItem.FireCommandEvent("Filter", new Pair("EqualTo", this.UniqueName));
                }
                else
                    // treat everything else like a string  
                    filterItem.FireCommandEvent("Filter", new Pair("Contains", this.UniqueName));
            }
            public object ListDataSource
            {
                get
                {
                    return this.listDataSource;
                }
                set
                {
                    listDataSource = value;
                }
            }
 
            public DataTable ListDataSource2
            {
                get
                {
                    // Build list values
                    DataTable dtDropDownValues = new DataTable();
                    dtDropDownValues.Columns.Add(this.DataField);
 
                    DataRow _dr = dtDropDownValues.NewRow();
                    _dr[this.DataField] = "Mike";
                    dtDropDownValues.Rows.Add(_dr);
 
                    DataRow _dr2 = dtDropDownValues.NewRow();
                    _dr2[this.DataField] = "Rob";
                    dtDropDownValues.Rows.Add(_dr2);
 
                    DataRow _dr3 = dtDropDownValues.NewRow();
                    _dr3[this.DataField] = "Jim";
                    dtDropDownValues.Rows.Add(_dr3);
 
                    return dtDropDownValues;
                }
            }
 
            //RadGrid calls this method when the value should be set to the filtering input control(s) 
            protected override void SetCurrentFilterValueToControl(TableCell cell)
            {
                base.SetCurrentFilterValueToControl(cell);
                DropDownList list = (DropDownList)cell.Controls[0];
                if (this.CurrentFilterValue != string.Empty)
                {
                    list.SelectedValue = this.CurrentFilterValue;
                }
            }
            //RadGrid calls this method to extract the filtering value from the filtering input control(s) 
            protected override string GetCurrentFilterValueFromControl(TableCell cell)
            {
                DropDownList list = (DropDownList)cell.Controls[0];
                return list.SelectedValue;
            }
            protected override string GetFilterDataField()
            {
                return this.DataField;
            }
        }

14 Answers, 1 is accepted

Sort by
0
Antonio Stoilkov
Telerik team
answered on 15 Oct 2012, 12:11 PM
Hi Mike,

Based on your description it is hard to determine the cause of the problem. However, you could achieve your scenario by following the help article and demo below which shows the same functionality implemented. We recommend using FilterTemplate functionality because is easier to build and maintain.

If your issue still persists or you want to build the functionality with custom column you could open a formal ticket and attach a sample project showing the unwanted behavior so we could advise you with the best possible solution.

Regards,
Antonio Stoilkov
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.
0
Mike
Top achievements
Rank 1
answered on 15 Oct 2012, 12:59 PM
Can you provide sample code that "dynamically" creates and implements a FilterTemplate?

Thanks,
Mike
0
Antonio Stoilkov
Telerik team
answered on 22 Oct 2012, 06:17 AM
Hello Mike,

I have assembled a sample page which demonstrates creation of filter template programatically in code behind. The idea is to follow the "Creating template columns programmatically" section in the help article below which describes how to implement template columns but to swap the template column with filter template.

Regards,
Antonio Stoilkov
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.
0
Kamal
Top achievements
Rank 1
answered on 04 Feb 2015, 05:38 PM
He Telerik Team

I'm really stuck in a fix. My problem is as below:

I'm using built in filters of RadGrid following Telerik demos itself. I'm binding it in codebehind with DataTable object (filtered at codebehind itself on active rows).

So as simple as it sounds. I want to set selection in the default Filter menu of the column named [Active].

It can be [X] (i.e. checked checkbox) and EqualTo selected from the adjacent drop down; or [] (i.e. unchecked checkbox) and NotEqualTo selected from the adjacent drop down..

Please help me.....

Thanks
Kamal
0
Kamal
Top achievements
Rank 1
answered on 05 Feb 2015, 09:07 AM
Hello Technical Team,

Please share your valuable suggestions for the previous question..

Thanks and regards
Kamal
0
Konstantin Dikov
Telerik team
answered on 09 Feb 2015, 11:35 AM
Hi Kamal,

I am not sure if I understand correctly your requirement, but if you need to set initial filters for the built-in filters of RadGrid, you could follow the steps provided in the following help article:
However, if you are using the CheckList filtering functionality, you will not be able to check specific items and change the filter function.

If you had something else in mind, please elaborate on the exact requirement and the scenario that you have.


Best Regards,
Konstantin Dikov
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.

 
0
Kamal
Top achievements
Rank 1
answered on 09 Feb 2015, 12:01 PM
Hello Konstantin

Below is the required ASPX and CS code.. You may notice I have a column named [Active] and I'm using built-in filters.

You can see that I'm binding the grid in code behind by active rows of a DataTable at first by default. I just need to set selection accordingly on the filter of the column named [Active] when page has loaded in the browser. I hope you got my point.


------------------ASPX code starts

<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
                                <ClientEvents OnRequestStart="requestStart" OnResponseEnd="requestEnd" />
                            </telerik:RadAjaxManager>
                            <telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="True" AllowSorting="True"
                                AutoGenerateColumns="False"
                                OnNeedDataSource="RadGrid1_NeedDataSource" OnUpdateCommand="RadGrid1_UpdateCommand"
                                OnInsertCommand="RadGrid1_InsertCommand" OnItemDataBound="RadGrid1_ItemDataBound" OnItemCommand="RadGrid1_ItemCommand"
                                AllowFilteringByColumn="true"
                                Skin="Silk"
                                PageSize="10"
                                HeaderStyle-Font-Bold="true"
                                AlternatingItemStyle-BackColor="#f0f0f0">

                                <GroupingSettings CaseSensitive="false" />

                                <PagerStyle Mode="NextPrevAndNumeric" Position="TopAndBottom" />

                                <ExportSettings ExportOnlyData="True" IgnorePaging="True" OpenInNewWindow="true">
                                    <Pdf PageWidth="210mm" PageHeight="297mm" PaperSize="A4"></Pdf>
                                    <Excel FileExtension="xlsx" />
                                </ExportSettings>

                                <MasterTableView CommandItemDisplay="Top" DataKeyNames="AppID"
                                    CommandItemSettings-ShowExportToExcelButton="true">
                                    <Columns>
                                        <telerik:GridEditCommandColumn UniqueName="EditCommandColumn" HeaderStyle-Width="50px" Resizable="false" Reorderable="false" />
                                        <telerik:GridBoundColumn SortExpression="AppName" DataField="AppName" HeaderText="Application Name" />
                                        <telerik:GridHyperLinkColumn DataTextField="NoOfPermTypes" SortExpression="NoOfPermTypes"
                                            HeaderText="# of Permission Types" DataNavigateUrlFields="AppID"
                                            DataNavigateUrlFormatString="ApplicationPermission.aspx?AppID={0}" />

                                        <telerik:GridBoundColumn DataField="Active" HeaderText="Active" HeaderStyle-Width="60px" Resizable="false"
                                            AllowFiltering="false" AllowSorting="false" />

                                        <telerik:GridBoundColumn SortExpression="WebBased" DataField="WebBased" HeaderText="Web Based"
                                            HeaderStyle-Width="150px" Resizable="false" />
                                        <telerik:GridBoundColumn SortExpression="ModifiedOn" DataField="ModifiedOn" HeaderText="Updated On" DataFormatString="{0:d-MMM-yyyy hh:mm tt}" />
                                        <telerik:GridBoundColumn SortExpression="ModifiedBy" DataField="ModifiedBy" HeaderText="Updated By" />
                                    </Columns>
                                    <EditFormSettings EditFormType="Template" CaptionFormatString="Add/Edit Application"
                                        FormCaptionStyle-Font-Bold="true">
                                        <PopUpSettings Width="485px" Modal="true" />
                                        <FormTemplate>
                                            <table id="Table3" cellpadding="2" cellspacing="1" border="0" class="module">
                                                <tr>
                                                    <td>Application Name:</td>
                                                    <td>
                                                        <asp:TextBox ID="txtAppName" runat="server" Text='<%# Bind("AppName") %>' MaxLength="50" />
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>Web Based:</td>
                                                    <td>
                                                        <asp:CheckBox ID="chkWebBased" runat="server" Enabled='<%# (Container is GridEditFormInsertItem) ? false : true %>'
                                                            Checked='<%# (DataBinder.Eval(Container.DataItem,"WebBased")==DBNull.Value ? true:Eval("WebBased"))%>' />
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>Active:</td>
                                                    <td>
                                                        <asp:CheckBox ID="chkActive" runat="server" Enabled='<%# (Container is GridEditFormInsertItem) ? false : true %>'
                                                            Checked='<%# (DataBinder.Eval(Container.DataItem,"Active")==DBNull.Value ? true:Eval("Active"))%>' />
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2" style="height: 20px;">
                                                        <asp:Label ID="lblError1" ForeColor="Red" runat="server"></asp:Label>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td></td>
                                                    <td>
                                                        <asp:Button ID="btnUpdate" Text='<%# (Container is GridEditFormInsertItem) ? "Insert" : "Update" %>'
                                                            runat="server" CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'
                                                            CssClass="button" />
                                                        &nbsp;
                                                        <asp:Button ID="btnCancel" Text="Cancel" runat="server" CausesValidation="False"
                                                            CommandName="Cancel" CssClass="button" />
                                                    </td>
                                                </tr>
                                            </table>
                                        </FormTemplate>
                                    </EditFormSettings>
                                </MasterTableView>
                                <ClientSettings AllowColumnsReorder="true" ColumnsReorderMethod="Reorder" ReorderColumnsOnClient="true">
                                    <ClientEvents OnRowDblClick="RowDblClick" OnPopUpShowing="onPopUpShowing" />
                                    <Resizing AllowRowResize="True" EnableRealTimeResize="True" ResizeGridOnColumnResize="True"
                                        AllowColumnResize="True" />
                                </ClientSettings>
                            </telerik:RadGrid>

------------------ASPX code ends


------------------CS code starts

using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web.UI;
using System.Linq;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using UPMLibrary;

namespace UserPermissionManager
{
    public partial class Applications : Page
    {
        AppPermission objApp = new AppPermission();
        Users objusers = new Users();

        public DataTable BindApplications()
        {
            //the table index (.Tables[1]) in the below statement is done
            //for TEMPORARY SUPPORT of old UPM and must changed back to (.Tables[0])
            //after this new UPM is rolled OUT
            /********************************************************************************************************************************************/
            DataView aView = objApp.ListApplications().Tables[1].DefaultView;
            /********************************************************************************************************************************************/

            aView.RowFilter = "Active=" + (true).ToString();

            return aView.ToTable();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ((HtmlGenericControl)this.Master.FindControl("liApps")).Attributes.Add("class", "SelectedMainMenu");

            if (!IsPostBack)
            {
                if (Session["PERMISSIONLOGONUSER"] != null)
                    objApp.CurrentUser = Session["PERMISSIONLOGONUSER"].ToString();
                else
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "document.getElementById('CTP_hdUserName').value = document.getElementById('lblSupplier').innerText;", true);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            RadGrid1.MasterTableView.EditMode = (GridEditMode)Enum.Parse(typeof(GridEditMode), "PopUp");
            GridFilterMenu menu = RadGrid1.FilterMenu;
            int i = 0;
            while (i < menu.Items.Count)
            {
                if (menu.Items[i].Text == "NoFilter" ||
                    menu.Items[i].Text == "Contains" ||
                    menu.Items[i].Text == "DoesNotContain" ||
                    menu.Items[i].Text == "StartsWith" ||
                    menu.Items[i].Text == "EndsWith" ||
                    menu.Items[i].Text == "EqualTo" ||
                    menu.Items[i].Text == "NotEqualTo"
                    )
                    i++;
                else
                    menu.Items.RemoveAt(i);
            }
        }

        private DataTable ApplicationsTable
        {
            get
            {
                object obj = Session["Applications"];
                DataTable myDataTable = new DataTable();
                if (obj != null)
                    myDataTable = (DataTable)obj;
                else
                    myDataTable = BindApplications();

                Session["Applications"] = myDataTable;
                return myDataTable;
            }
        }

        protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = ApplicationsTable;
            ApplicationsTable.PrimaryKey = new DataColumn[] { ApplicationsTable.Columns["AppID"] };
        }

        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            //if (e.Item is GridFilteringItem)
            //{
            //    GridFilteringItem filterItem = e.Item as GridFilteringItem;
            //    //gridfilte
            //    //filterItem.
            //}
            if (e.Item is GridDataItem)
            {
                //Get the instance of the right type
                GridDataItem dataBoundItem = e.Item as GridDataItem;

                //Check the formatting condition
                if (dataBoundItem["Active"].Text.ToLower() == "true")
                {
                    dataBoundItem["Active"].Text = "YES";
                    dataBoundItem["Active"].ForeColor = dataBoundItem["AppName"].ForeColor = Color.Green;
                    dataBoundItem["Active"].Font.Bold = dataBoundItem["AppName"].Font.Bold = true;

                }
                else
                {
                    dataBoundItem["Active"].Text = "NO";
                    dataBoundItem["Active"].ForeColor = dataBoundItem["AppName"].ForeColor = Color.Red;
                }
                if (dataBoundItem["WebBased"].Text.ToLower() == "true")
                {
                    dataBoundItem["WebBased"].Text = "YES";
                    dataBoundItem["WebBased"].ForeColor = Color.Green;
                    dataBoundItem["WebBased"].Font.Bold = true;
                }
                else
                {
                    dataBoundItem["WebBased"].Text = "NO";
                    dataBoundItem["WebBased"].ForeColor = Color.Red;
                }
            }
            if ((e.Item is GridEditableItem) && (e.Item.IsInEditMode))
            {
                GridEditableItem editform = (GridEditableItem)e.Item;
                TextBox txtAppName = (TextBox)editform.FindControl("txtAppName");
                Button btnUpdate = (Button)editform.FindControl("btnUpdate");

                btnUpdate.Attributes.Add("onclick",

                    "if($('#" + txtAppName.ClientID + "').val() == '') { $('#"
                    + txtAppName.ClientID + "').effect('shake'); $('#" + txtAppName.ClientID + "').focus(); return false; }"

                    + "alertfunction('Application saved.');"

                    );
            }
        }

        protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            TextBox txtAppName = (TextBox)editedItem.FindControl("txtAppName");
            CheckBox chkWebBased = (CheckBox)editedItem.FindControl("chkWebBased");
            CheckBox chkActive = (CheckBox)editedItem.FindControl("chkActive");
            Label lblError1 = (Label)editedItem.FindControl("lblError1");

            //Prepare new row to add it in the DataSource
            string sAppID = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["AppID"].ToString();
            DataRow[] changedRows = ApplicationsTable.Select("AppID = " + sAppID);

            Label lblError = new Label();
            RadGrid1.Controls.Add(lblError);

            //Update new values

            changedRows[0].BeginEdit();
            try
            {
                Hashtable newValues = new Hashtable();
                objApp.APPID = Convert.ToInt32(sAppID);
                newValues["AppName"] = objApp.AppName = txtAppName.Text;
                newValues["WebBased"] = objApp.WebBased = (chkWebBased.Checked) ? 1 : 0;
                newValues["Active"] = objApp.AppStatus = (chkActive.Checked) ? 1 : 0;
                newValues["ModifiedOn"] = DateTime.Now;
                if (objApp.CurrentUser == null || objApp.CurrentUser == "")
                {
                    if (((Main)this.Master).UserName != "")
                        Session["PERMISSIONLOGONUSER"] = newValues["ModifiedBy"] = objApp.CurrentUser = ((Main)this.Master).UserName;
                    else
                        Session["PERMISSIONLOGONUSER"] = newValues["ModifiedBy"] = objApp.CurrentUser = hdUserName.Value;
                }

                objApp.ChangeAppStatus();

                foreach (DictionaryEntry entry in newValues)
                    changedRows[0][(string)entry.Key] = entry.Value;

                changedRows[0].EndEdit();
                ApplicationsTable.AcceptChanges();

                lblError.Text = "Application updated successfully.";
                lblError.ForeColor = Color.Green;
            }
            catch (Exception ex)
            {
                changedRows[0].CancelEdit();
                lblError1.Text = "Unable to update Application. Reason: " + ex.Message;
                e.Canceled = true;
            }
        }

        protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            TextBox txtAppName = (TextBox)editedItem.FindControl("txtAppName");
            CheckBox chkWebBased = (CheckBox)editedItem.FindControl("chkWebBased");
            CheckBox chkActive = (CheckBox)editedItem.FindControl("chkActive");
            Label lblError1 = (Label)editedItem.FindControl("lblError1");

            //Create new row in the DataSource
            DataRow newRow = ApplicationsTable.NewRow();

            Label lblError = new Label();
            RadGrid1.Controls.Add(lblError);

            //Insert new values

            //make sure that unique primary key value is generated for the inserted row
            try
            {
                Hashtable newValues = new Hashtable();

                objApp.APPID = 0;
                newValues["AppName"] = objApp.AppName = txtAppName.Text;
                newValues["NoOfPermTypes"] = 0;
                newValues["WebBased"] = objApp.WebBased = (chkWebBased.Checked) ? 1 : 0;
                newValues["Active"] = objApp.AppStatus = (chkActive.Checked) ? 1 : 0;
                newValues["ModifiedOn"] = DateTime.Now;
                if (objApp.CurrentUser == null || objApp.CurrentUser == "")
                {
                    if (((Main)this.Master).UserName != "")
                        Session["PERMISSIONLOGONUSER"] = newValues["ModifiedBy"] = objApp.CurrentUser = ((Main)this.Master).UserName;
                    else
                        Session["PERMISSIONLOGONUSER"] = newValues["ModifiedBy"] = objApp.CurrentUser = hdUserName.Value;
                }

                newValues["AppID"] = objApp.ChangeAppStatus();

                foreach (DictionaryEntry entry in newValues)
                    newRow[(string)entry.Key] = entry.Value;

                ApplicationsTable.Rows.Add(newRow);
                ApplicationsTable.AcceptChanges();

                lblError.Text = "Application inserted successfully.";
                lblError.ForeColor = Color.Green;
            }
            catch (Exception ex)
            {
                lblError1.Text = "Unable to insert Application. Reason: " + ex.Message;
                e.Canceled = true;
            }
        }

        protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.ExportToExcelCommandName)
                RadGrid1.MasterTableView.ExportToExcel();
        }
    }
}

------------------CS code ends


0
Konstantin Dikov
Telerik team
answered on 12 Feb 2015, 11:58 AM
Hi Kamal,

Although that I have examined your current implementation, I will need some further explanation on the exact requirement that you have. Can you please elaborate on what exactly you mean with "I just need to set selection accordingly on the filter of the column named [Active]"?

Additionally, I have noticed that you are disabling the filter for the Active column and furthermore, before you provide the data to the grid you are setting a filter in the DataTable object for the Active column. This will prevent the grid for performing any filtering operations over the Active field, because you will have only "true" values available.

I am looking forward to your reply with detailed information on the exact requirement. 


Regards,
Konstantin Dikov
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.

 
0
Kamal
Top achievements
Rank 1
answered on 20 Feb 2015, 05:24 AM
Hello Konstantin

I'm sorry for confusion. I wish I could show you but somehow the screen shots does not attach while replying to/creating posts on the forums. :(

I'll try to explain.

Agreed, in my code I've disabled the filter on [Active] column.

Suppose I'm coming on this page with this URL.....    "Applications.aspx?AppName=CATS"

In the code I can filter (the DataTable and bind it with the RadGrid). Now I need to pre-select the filter in the "Application Name" column in UI page ("Applications.aspx") as below:

Column name                Filter textbox value                Filter DropDown value selection
"Application Name"        "CATS"                                  "Contains"


I hope you got this. I really need this in my project.







0
Kamal
Top achievements
Rank 1
answered on 20 Feb 2015, 07:18 AM
More:

Here "pre-select the filter in UI" means that I need to set the filter selection in the code behind exactly after filtering the DataTable and rebinding the RadGrid. Something like below pseudo code.

-----
DataTable.Select("where appname like '%" + Request.QueryString["AppName"] + "%'");
RadGrid1.Rebind();

//available filter options
//menu.Items[0].Text = "NoFilter"
//menu.Items[1].Text = "Contains"
//menu.Items[2].Text = "DoesNotContain"
//menu.Items[3].Text = "StartsWith"
//menu.Items[4].Text = "EndsWith"
//menu.Items[5].Text = "EqualTo"
//menu.Items[5].Text = "NotEqualTo"

RadGrid1.Columns[1].FilterMenu.Items[1].Selected = true;    //in "Items[1]", 1 is the index of the available options shown above
RadGrid1.Columns[1].FilterMenu.Value = Request.QueryString["AppName"];
-----

I hope it should be more clear now.

Thanks
Kamal
0
Kamal
Top achievements
Rank 1
answered on 21 Feb 2015, 05:06 PM
Hello Team

Please help me with this. I really need it. I hope my requirement is not illogical. :(

Thanks
Kamal
0
Kamal
Top achievements
Rank 1
answered on 24 Feb 2015, 01:30 PM
Hello Team

Please help me with this.

Thanks
Kamal
0
Konstantin Dikov
Telerik team
answered on 24 Feb 2015, 03:12 PM
Hello Kamal,

In one of my previous posts I have pointed you to the following help article, where you will find out how to set initial filter for RadGrid:
From what I understand from your descriptions, this is exactly what you need to implement, so please follow the suggestions from the help article and apply your default filter within the server-side OnPreRender event of the grid:
protected void RadGrid1_PreRender(object sender, System.EventArgs e)
{
    if (!Page.IsPostBack)
    {
        RadGrid1.MasterTableView.FilterExpression = "([Country] LIKE \'%Germany%\') ";
        GridColumn column = RadGrid1.MasterTableView.GetColumnSafe("Country");
        column.CurrentFilterFunction = GridKnownFunction.Contains;
        column.CurrentFilterValue = "Germany";
        RadGrid1.MasterTableView.Rebind();
    }
}



Regards,
Konstantin Dikov
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.

 
0
Kamal
Top achievements
Rank 1
answered on 03 Mar 2015, 05:55 AM
Thanks much Konstantin for your time and sorry for missing the suggestion in earlier. It solved the issue.

Thanks
Kamal
Tags
Grid
Asked by
Mike
Top achievements
Rank 1
Answers by
Antonio Stoilkov
Telerik team
Mike
Top achievements
Rank 1
Kamal
Top achievements
Rank 1
Konstantin Dikov
Telerik team
Share this question
or