I am creating an applica开发者_运维知识库tion where I require to add dynamic checkbox list. Please anyone tell me how to add dynamic checkbox list using C#.
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.
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);
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);
精彩评论