Bind Checkbox dynamically in DataList

This post shows that how to retrieve value from database and bind checkbox in Datalist. Here the checkbox will bind dynamically using itemdatabound event of datalist.

First Create 2 tables:

1st table:
CREATE TABLE [dbo].[TBL_CONTROL](
            [CONTROL_ID] [int] primary key IDENTITY(1,1) NOT NULL,
            [CONTROL_NAME] [varchar](50) NULL
)

2nd table:  
CREATE TABLE [dbo].[TBL_ATTRIBUTE](
            [ID] [int] primary key IDENTITY(1,1) NOT NULL,
            [ATTRIBUTE_ID] [int] NOT NULL,
            [CONTROL_ID] [int] NULL,
           
)

Here we first bind the first table in DataList. Then check whether the id of first table present in second table or not, if that id is present in second table then the checkbox will checked otherwise it will unchecked. 

Then add the entity in your solution and create object of that entity in your page. Like
DemoEntities ob=new DemoEntities();

Add DataList in Design Page with Checkbox:

<asp:DataList ID="datalst" runat="server" ShowHeader="false" OnItemDataBound="datalst_ItemDataBound" Width="100%" GridLines="None" RepeatColumns="4">
<ItemTemplate>
<div style="width:120px;">
<telerik:RadCheckBox ID="chk" runat="server" AutoPostBack="false"></telerik:RadCheckBox>
<telerik:RadLabel ID="id" runat="server" Text='<%# Bind("CONTROL_ID") %>' Visible="false"></telerik:RadLabel>
<telerik:RadLabel ID="scale" runat="server" Text='<%# Bind("CONTROL_NAME") %>'></telerik:RadLabel>
</div>
</ItemTemplate>
</asp:DataList>

Then Bind the first table in DataList in pageload:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                datalst.DataSource=ob.TBL_CONTROL.ToList();
                  datalst.DataBind();
            }
        }

Then write code for to bind checkbox:

Use ItemDataBound event for binding checkbox in datalist at page load time.
protected void datalst_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
try
{
int check = Convert.ToInt32(((RadLabel)e.Item.FindControl("id")).Text);
var cg =(from a in ob.TBL_CONTROL.ToList()
                                                           join b in ob.TBL_ATTRIBUTE.ToList()
                                                            where b.ATTRIBUTE_ID==1 && a.CONTROL_ID==check
                                                            select new        
                                                             {
                                                                 a.CONTROL_ID,
                                                                 a.CONTROL_NAME,
                                                             }).ToList();
if (cg.ToList().Count == 0)
{
((RadCheckBox)e.Item.FindControl("chk")).Checked = false;
}
else
{
((RadCheckBox)e.Item.FindControl("chk")).Checked = true;
}
}
catch
{ }
}
}

Post a Comment

1 Comments