user99
user99

Reputation: 61

How to create dynamic checkbox in asp.net

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#.

Upvotes: 5

Views: 21984

Answers (3)

Andy Clark
Andy Clark

Reputation: 3523

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.

Upvotes: 9

emre nevayeshirazi
emre nevayeshirazi

Reputation: 19241

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);

Upvotes: 2

Bobby
Bobby

Reputation: 1604

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);   

Upvotes: 2

Related Questions