How to generate Dynamic Checkbox in ASP.Net using C#


Introduction

 

As a programmer we need to know about the static as well as dynamic controls. It's not necessary that always we will be using the static controls. Many programmers are having a mind setup like if they want the dynamic controls they have to write many lines of code but it's not like that.

 

Suppose we want to add dynamic control to a Panal control.So, what is the approach for that?

Following code will explain how to create the dynamic checkboxes.

 

Source Code:

 

//Drag and drop panal on the Webpage.

//After drag and drop following code will be generated automatically

protected System.Web.UI.WebControls.Panel PnlControl;

//Declare a CheckBox

CheckBox chkList1;

private void Page_Load(object sender, System.EventArgs e)

          {

                .

                .

                //Page load code goes here

                .

                .

          }

#region dyanamic checkboxes

//Function to generate the dyanamic checkboxes

private void AddCheckboxes(string strCheckboxText)

          {

                try

                {

                     if(PnlTimeExpence.HasControls())

                     {

                           return;

                     }

                     for(int intControlIndex=0;intControlIndex=5;intControlIndex++)

                     {

                           chkList1 =new CheckBox();

                           chkList1.Text = strCheckboxText;

                           chkList1.ID="Chk"+intControlIndex;

                           chkList1.Font.Name = "Verdana";

                           chkList1.Font.Size = 9;

                           PnlControl.Controls.Add(chkList1);

                           PnlControl.Controls.Add(new LiteralControl("<br>"));

                     }

                }

                catch(Exception exp)

                {

                     throw new Exception(exp.Message);

                }

          }

#endregion


Similar Articles