Bibu
Bibu

Reputation: 201

error creating a checkboxlist

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["erp"].ConnectionString);
con.Open();
string intero = "Select * from judete";
SqlCommand cmd = new SqlCommand(intero, con);

SqlDataReader rdr;

rdr = cmd.ExecuteReader();

while (rdr.Read())
{
    CheckBoxList check = new CheckBoxList();
    check.Visible = true;

    check.Items.Add(new ListItem(rdr[1].ToString()));
    Panel1.Controls.Add(check);

    foreach (ListItem item in this.check)
    {

    }

I want to make a foreach in the checkboxlist but I get an error that I don't have a checkboxlist check despite that I'm creating it.Do you have any idea why my checkboxlist check isn't recognized? I'm using c# in an asp.net application.

Upvotes: 0

Views: 180

Answers (2)

Shyju
Shyju

Reputation: 218932

Since you added the CheckBoxList from code, you wont get the items from this. So use FindControl Method to get the Item. You should be giving an ID to your control when you create that

CheckBoxList check = new CheckBoxList();
check.ID="myCheck";

You can get the item like this

 CheckBoxList myCheck=(CheckBoxList) Panel1.FindControl("myCheck");

You can loop thru the Items collection of Checkbox list like this now

foreach (ListItem item in myCheck.Items)
{
     item.Text = rdr.GetString(2); //or whatever with GetOrdinal
}

Are you sure you want to create an instance of the Checkbox list inside the While loop or you just want to create only one instance of that (outside the while) and add the items from your table to the Checkbox list inside the while loop ?

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174467

Remove the this. before check in the foreach loop and add .Items after it:

foreach (ListItem item in check.Items)

Reasons:

  • check is a local variable and not a member variable.
  • You want to enumerate the Items of the CheckBoxList.

Upvotes: 2

Related Questions