Enigma34
Enigma34

Reputation: 347

generate Dynamic Checkbox in ASP.Net

plz tell me whats wrong in code bcz i m not able to add control on page. i m getting the values right & if i just CheckBoxList2.Items.Add(row["subj_nme"].ToString()); the check box get created

if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    chkList1 = new CheckBox();
                    chkList1.Text = row["subj_nme"].ToString();
                    chkList1.ID = row["subjid"].ToString();
                    chkList1.Checked = true;
                    chkList1.Font.Name = "Verdana";
                    chkList1.Font.Size = 12;
                    CheckBoxList2.Controls.Add(chkList1);
                }
            }

Upvotes: 0

Views: 1604

Answers (1)

Amit
Amit

Reputation: 22086

I think you can use this code for binding your CheckBoxList2 to DataTable as follow.

CheckBoxList2.DataSource = ds.Tables[0];
CheckBoxList2.DataTextField = "subj_nme";
CheckBoxList2.DataValueField = "subjid";
CheckBoxList2.DataBind();
CheckBoxList2.Font.Name = "Verdana";
CheckBoxList2.Font.Size = 12;

To check them all you can do this

for(int i=0;i<CheckBoxList2.Items.Count;i++)
{
CheckBoxList2.Items[i].Selected = true;
}

Upvotes: 2

Related Questions