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

How to get reference to a checkbox in a grid that was added programmatically

4 Answers 200 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Dan Harvey
Top achievements
Rank 2
Dan Harvey asked on 28 Mar 2012, 11:06 PM
Hello,

I have added several checkbox columns to a grid programmatically and I was wondering how I can retrieve a reference to them from server side code.

I am adding the columns this way:
var templateColumn = new GridTemplateColumn();
templateColumn.UniqueName = role.RoleName;
templateColumn.ItemTemplate = new RoleColumn(role);
  
// add the dynamically created columns to the grid
dgLoginRequest.MasterTableView.Columns.Add(templateColumn);
  
public class RoleColumn : ITemplate
    {
  
        protected CheckBox roleCheckbox;
        private Role _role;
  
        public RoleColumn(Role role)
        {
            _role = role;
        }
  
        public void InstantiateIn(Control container)
        {
            roleCheckbox = new CheckBox { ID = "chkReader"};
            roleCheckbox.AutoPostBack = false;
            roleCheckbox.DataBinding += new EventHandler(roleCheckbox_DataBinding);
            container.Controls.Add(roleCheckbox);
        }
  
        private void roleCheckbox_DataBinding(object sender, EventArgs e)
        {
            var cBox = (CheckBox)sender;
            var container = (GridDataItem)cBox.NamingContainer;
            cBox.Checked = (bool)DataBinder.Eval((container.DataItem), "Roles[" + _role.RoleID +"]"); 
        }
  
    }


And I bind the grid to an data source (ArrayList of customObject).  On a postback, I want to be able to get a refence to the checkboxes I added.

I am using the following code but it returns me null:
foreach (GridDataItem item in dgLoginRequest.MasterTableView.Items)
            {
                var ads = item.DataItem;
                var cbx = (CheckBox) item.FindControl("chkReader");
            }

How can I get a reference to this checkbox on lets say a button click (i.e. not using the rad grid events)?

4 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 29 Mar 2012, 07:04 AM
Hi Dan Harvey,

I have created RadGrid programmatically using SqlDataSource and I could access the CheckBox on Button Click. Please take a look into the following code.

ASPX:
<telerik:RadGrid ID="RadGrid1" runat="server" ></telerik:RadGrid>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" />
 
<asp:SqlDataSource ID="SqlDataSource1" ConnectionString="<%$ConnectionStrings:NorthwindConnectionString3%>" runat="server" SelectCommand="select  * from  Employees" ></asp:SqlDataSource>

C#:
protected void Page_Init(object sender, EventArgs e)
{
 
    RadGrid1.DataSourceID = "SqlDataSource1";
    RadGrid1.PageSize = 2;
    RadGrid1.AllowPaging = true;
    RadGrid1.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
    RadGrid1.PagerStyle.AlwaysVisible = true;
    RadGrid1.AutoGenerateColumns = false;
    GridTemplateColumn templateColumn;
    templateColumn = new GridTemplateColumn();
    RadGrid1.MasterTableView.Columns.Add(templateColumn);
    templateColumn.ItemTemplate = new MyTemplate();
    templateColumn.HeaderText = "TemplateColumn";
}
private class MyTemplate : ITemplate
{
    protected CheckBox roleCheckbox;
    public MyTemplate()
    {
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
        roleCheckbox = new CheckBox { ID = "chkReader" };
        roleCheckbox.AutoPostBack = false;
        roleCheckbox.Text = "checkk";
        roleCheckbox.DataBinding += new EventHandler(roleCheckbox_DataBinding);
        container.Controls.Add(roleCheckbox);
    }
    void roleCheckbox_DataBinding(object sender, EventArgs e)
    {
        var cBox = (CheckBox)sender;
        var container = (GridDataItem)cBox.NamingContainer;
        cBox.Checked = (bool)DataBinder.Eval((container.DataItem), "IsActive");
    }
}
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
        {
            CheckBox chk = (CheckBox)item.FindControl("chkReader");
        }
 
    }

Please provide the complete code if it doesn't help.

Thanks,
-Shinu.
0
Dan Harvey
Top achievements
Rank 2
answered on 29 Mar 2012, 01:47 PM
Hello,

Thank you for your reply.  This didn't help.  Here is my entire application:

namespace WebApplication2
{
  
    [Serializable]
    public class Role
    {
        public int RoleID { get; set; }
        public string RoleName { get; set; }        
    }
  
    [Serializable]
    public class Entity
    {
        public int EntityID { get; set; }
  
        public string EntityName { get; set; }
  
        public Dictionary<int, bool> Roles { get; set; }
    }
  
    public class RoleColumn : ITemplate
    {
  
        protected CheckBox roleCheckbox;
        private Role _role;
  
  
        public RoleColumn(Role role)
        {
            _role = role;
        }
  
        public void InstantiateIn(Control container)
        {
            roleCheckbox = new CheckBox { ID = "chk" + _role.RoleName };
            roleCheckbox.AutoPostBack = false;
            roleCheckbox.DataBinding += new EventHandler(roleCheckbox_DataBinding);
            container.Controls.Add(roleCheckbox);
        }
  
        private void roleCheckbox_DataBinding(object sender, EventArgs e)
        {
            var cBox = (CheckBox)sender;
            var container = (GridDataItem)cBox.NamingContainer;
            cBox.Checked = (bool)DataBinder.Eval((container.DataItem), "Roles[" + _role.RoleID + "]"); 
        }
  
    }
  
}


<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:ScriptManager runat="server"></asp:ScriptManager>
    <asp:Button ID="btnSubmit" runat="server" Text="Add" OnClick="btnSubmit_Click"/>
  
    <telerik:RadGrid ID="dgLoginRequest" 
                     runat="server"
                     EnableViewState="True" 
                     AllowSorting="True"
                     AllowPaging="True" 
                     AllowAutomaticUpdates="True"
                     EnableAJAX="true" 
                     EnableOutsideScripts="true" 
                     GridLines="None"
                     GroupingSettings-GroupContinuesFormatString=""
                     OnNeedDataSource="dgLoginRequest_NeedDataSource">
                       
        <ClientSettings>
            <Selecting CellSelectionMode="None" AllowRowSelect="False" />
        </ClientSettings>
  
        <MasterTableView AllowAutomaticDeletes="True"
                            AllowAutomaticUpdates="True" 
                            AutoGenerateColumns="False"
                            CommandItemDisplay="None"
                            DataKeyNames="EntityID" 
                            Width="100%">
                                                          
        <CommandItemSettings ExportToPdfText="Export to PDF" />
        <RowIndicatorColumn>
            <HeaderStyle Width="20px" />
        </RowIndicatorColumn>
        <ExpandCollapseColumn>
            <HeaderStyle Width="20px" />
        </ExpandCollapseColumn>
                                                      
            <GroupHeaderItemStyle CssClass="align" />
  
            <Columns>
  
                <telerik:GridBoundColumn DataField="EntityID" UniqueName="EntityID" HeaderStyle-HorizontalAlign="Center" HeaderText="Entity ID" ItemStyle-HorizontalAlign="Left" SortExpression="EntityID" Visible="False">
                    <HeaderStyle HorizontalAlign="Center" />
                    <ItemStyle HorizontalAlign="Left" />
                </telerik:GridBoundColumn>
  
                <telerik:GridBoundColumn DataField="EntityName" UniqueName="EntityName" HeaderText="Entity Name" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Left" SortExpression="EntityName" >
                    <HeaderStyle HorizontalAlign="Center" />
                    <ItemStyle HorizontalAlign="Left" />
                </telerik:GridBoundColumn>
                                                              
                                                              
                <telerik:GridTemplateColumn HeaderText=" ">
                    <ItemTemplate>
                        <asp:ImageButton ID="btnDelete" 
                                            runat="server" 
                                            CausesValidation="False"
                                            ImageUrl="../Login/Images/Delete.gif"  
                                            ToolTip="Delete Record" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
  
            </Columns>
                                                         
            <EditFormSettings>
                <EditColumn FilterControlAltText="Filter EditCommandColumn column">
                </EditColumn>
            </EditFormSettings>
  
        </MasterTableView>
        <FilterMenu EnableTheming="True" Skin="WebBlue">
            <CollapseAnimation Duration="200" Type="OutQuint" />
        </FilterMenu>
        </telerik:RadGrid>
  
</asp:Content>


public partial class Default : System.Web.UI.Page
    {
          
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["Roles"] = new ArrayList();
                var role1 = new Role() {RoleID = 1, RoleName = "Reader"};
                var role2 = new Role() {RoleID = 2, RoleName = "Share"};
                var role3 = new Role() {RoleID = 3, RoleName = "PrivateReader"};
                var role4 = new Role() {RoleID = 4, RoleName = "Drop"};
                Roles.Add(role1);
                Roles.Add(role2);
                Roles.Add(role3);
                Roles.Add(role4);
  
                DefineGridStructure();
            }
        }
  
  
        public void DefineGridStructure()
        {
  
            foreach (Role role in Roles)
            {
                var templateColumn = new GridTemplateColumn();
                templateColumn.UniqueName = role.RoleName;
                templateColumn.ItemTemplate = new RoleColumn(role);
                templateColumn.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
  
                // add the dynamically created columns to the grid
                dgLoginRequest.MasterTableView.Columns.Add(templateColumn);
            }
  
        }
  
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                ViewState["DataSource"] = new ArrayList();
                var entity0 = new Entity() { EntityID = 1, EntityName = "Test0", Roles = GetRoles() };
                var entity1 = new Entity() { EntityID = 1, EntityName = "Test1", Roles = GetRoles() };
                var entity2 = new Entity() { EntityID = 1, EntityName = "Test2", Roles = GetRoles() };
                DataSource.Add(entity0);
                DataSource.Add(entity1);
                DataSource.Add(entity2);
                BindDataGrid();
            }
        }
  
        public void BindDataGrid()
        {
            try
            {
               // DefineGridStructure();
                dgLoginRequest.DataSource = DataSource;
                dgLoginRequest.DataBind();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
  
        private Dictionary<int, bool> GetRoles()
        {
            var dict = new Dictionary<int, bool>();
            foreach (Role role in Roles)
            {
                dict.Add(role.RoleID, false);
            }
  
            return dict;
        }
  
        public ArrayList Roles { get { return (ArrayList)ViewState["Roles"]; } }
  
        public ArrayList DataSource { get { return (ArrayList)ViewState["DataSource"]; } }
  
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            // update datasource first with any checkbox clicks
            foreach (GridDataItem item in dgLoginRequest.MasterTableView.Items)
            {
                //CHECKBOX STILL COMING IN AS NULL
                var cbx = (CheckBox)item.FindControl("chkReader");
            }
  
            var entity4 = new Entity() { EntityID = 1, EntityName = "Test4", Roles = GetRoles() };
            DataSource.Add(entity4);
        }
  
        protected void dgLoginRequest_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            dgLoginRequest.DataSource = DataSource;
            // no need to call databind, this event automatically does it
        }
  
    }



The checkbox still comes in as null

Also, when the page refreshes, my columns are lost that I added.

Thanks
0
Shinu
Top achievements
Rank 2
answered on 29 Mar 2012, 01:58 PM
Hello Dan,

RadGrid does not support mixing declarative grid columns with grid columns added dynamically at runtime. You should either create all the columns in the grid programmatically, or else define them all in the ASPX file. Check the following help documentation which explains how to create the RadGrid entirely in code-behind.
Programmatic Creation.

Thanks,
Shinu.
0
Dan Harvey
Top achievements
Rank 2
answered on 29 Mar 2012, 11:46 PM
OK, thank you for your help
Tags
Grid
Asked by
Dan Harvey
Top achievements
Rank 2
Answers by
Shinu
Top achievements
Rank 2
Dan Harvey
Top achievements
Rank 2
Share this question
or