I have dynamically populated data to my checkboxlist from SqlServer data base.. using code
aspx
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(
ConfigurationManager.ConnectionStrings["testingCS"].ConnectionString);
cn.Open();
SqlCommand cmd1 = new SqlCommand("select * from tbl_vehicletypes", cn);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows) {
CheckBoxList1.DataSource = dr;
CheckBoxList1.DataTextField = "typedesc";
CheckBoxList1.DataValueField = "vehicletypeid";
CheckBoxList1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string[] arr = new string[10];
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
if (CheckBoxList1.Items[i].Selected==true)
arr[i] = CheckBoxList1.Items[i].Value;
foreach (string s in arr)
Label2.Text += s + "<br />";
Label2.Text = CheckBoxList1.Items.Count.ToString();
}
I tried using for loop and foreach as well but it didn't work out. The selected data is not getting added to string array..
Please help