Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic checkbox in asp.net

Tags:

c#

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

like image 998
user99 Avatar asked Aug 23 '11 10:08

user99


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.

like image 52
Andy Clark Avatar answered Oct 14 '22 19:10

Andy Clark


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);   
like image 33
Bobby Avatar answered Oct 14 '22 17:10

Bobby


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);
like image 38
emre nevayeshirazi Avatar answered Oct 14 '22 19:10

emre nevayeshirazi