CheckBoxList Binding options Dynamically
In general we make use of the CheckBox control to design a list of check boxes in the screen,
but what if we need to display a lot of checkboxes in a page say 25+, and if
the values and text for these checkboxes will vary dynamically.
Asp.Net offers a CheckBoxList control, to handle this situation, this control allows
data binding similar to a GridView or Dropdown List control, using which we can
bind a data source to the CheckBoxList
control.
Let us see on how to use this control.
In the .aspx page just add the CheckBoxList tag without adding any options as follows.
Select Name:
<tr>
<td style="text-align:left;>
Select Name:
<asp:CheckBoxList
ID="chkListNames"
runat="server" RepeatDirection="Vertical">
</asp:CheckBoxList>
</td>
</tr>
<tr>
<td style=" text-align:left;>
<asp:Button
ID="cmdSave"
runat="server"
Text="Save"
onclick="cmdSave_Click" />
<B>Selected Names:B>
<asp:Label
ID="lblNames"
runat="server">
</asp:Label>
</td>
</tr>
Then navigate to the code behind file and add
the required options as follows.
protected void
Page_Load(object sender, EventArgs e)
{
if
(!Page.IsPostBack)
{
//Data Access code to get
the options from the DB
chkListNames.DataSource = dtEmployee;
chkListNames.DataSource = dtEmployee;
chkListNames.DataValueField = "ID";
chkListNames.DataTextField = "Name";
chkListNames.DataBind();
}
}
protected void
cmdSave_Click(object sender, EventArgs e)
{
string
strNames = string.Empty;
foreach (ListItem chkItem in
chkListNames.Items)
{
if
(chkItem.Selected == true)
{
strNames += chkItem.Text + ", ";
}
}
//
lblNames.Text = strNames;
}
That’s it we have bound the options to the CheckBoxList control at runtime.
No comments:
Post a Comment