I am creating an application where I require to add dynamic checkbox list. Please anyone tell me how to add dynamic checkbox list using C#.
-
1what have you tried and where are you stuck? WinForms application, WPF or ASP.NET ?Matten– Matten2011-08-23 10:55:08 +00:00Commented Aug 23, 2011 at 10:55
-
When you mean dynamic, do you mean in code, or programically?Jethro– Jethro2011-08-23 10:55:41 +00:00Commented Aug 23, 2011 at 10:55
-
@Matten, I think it's ASP.NET as thats what the heading says.Jethro– Jethro2011-08-23 10:56:21 +00:00Commented Aug 23, 2011 at 10:56
-
1Possible duplicate post. stackoverflow.com/questions/626889/…Jethro– Jethro2011-08-23 10:58:20 +00:00Commented Aug 23, 2011 at 10:58
-
1@Jethro -- I should improve my reading skills :)Matten– Matten2011-08-23 11:18:25 +00:00Commented Aug 23, 2011 at 11:18
3 Answers
Put a placeHolder on your form with the ID placeHolder and add the following code to your Page_Load():
CheckBoxList cbList = new CheckBoxList();
for (int i = 0; i < 10; i++)
cbList.Items.Add(new ListItem("Checkbox " + i.ToString(), i.ToString()));
placeHolder.Controls.Add(cbList);
This will add 10 CheckBox objects within your CheckBoxList(cbList).
Use the following code to examine each CheckBox object within the CheckBoxList
foreach(ListItem li in cbList.Items)
{
var value = li.Value;
var text = li.Text;
bool isChecked = li.Selected;
}
The placeholder is used to add the CheckBoxList to the form at runtime, using a placeholder will give you more control over the web page where the CheckBoxList and its items will appear.
Comments
Here is an example
CheckBoxList chkList = new CheckBoxList();
CheckBox chk = new CheckBox();
chkList.ID = "ChkUser";
chkList.AutoPostBack = true;
chkList.RepeatColumns = 6;
chkList.DataSource = us.GetUserDS();
chkList.DataTextField = "User_Name";
chkList.DataValueField = "User_Id";
chkList.DataBind();
Panel pUser = new Panel();
if (pUserGrp != "")
{
pUser.GroupingText = pUserGrp ;
chk.Text = pUserGrp;
}
else
{
pUser.GroupingText = "Non Assigned Group";
chk.Text = "Non Assigned group";
}
pUser.Controls.Add(chk);
pUser.Controls.Add(chkList);
this.Form.Controls.Add(pUser);
Comments
At code behind you can create new ASP.NET Controls and you can add these controls to your page. All you need to do is to create new CheckBoxList Object and add ListItems to it. Finally, you need to add your CheckBoxList to your Page.
// Create CheckBoxList
CheckBoxList list= new CheckBoxList();
// Set attributes for CheckBoxList
list.ID = "CheckBoxList1";
list.AutoPostBack = true;
// Create ListItem
ListItem listItem = new ListItem();
// Set attributes for ListItem
listItem .ID = "ListItem1";
// Add ListItem to CheckBoxList
list.Items.Add(listItem );
// Add your new control to page
this.Form.Controls.Add(list);