mercredi 22 mars 2017

ASP.Net Iterate through checkboxes in panel

I have an asp panel that I populate with checkboxes dynamically:

string SheetName = "";
foreach (DataRow row in dt.Rows)
    {
        SheetName = row["TABLE_NAME"].ToString();
        CheckBox chk = new CheckBox();
        chk.ID = SheetName;
        chk.Text = SheetName;  
        pnlSheetNames.Controls.Add(new LiteralControl("<BR>"));
        pnlSheetNames.Controls.Add(chk);
        pnlSheetNames.Controls.Add(new LiteralControl("<BR>"));
        ViewState["controlsadded"] = true;
    }

This works fine. I want my user to check some boxes, and then I want to store the checked values in a list:

List<string> sheetNames = new List<string>();
sheetNames.Add("test");
foreach (CheckBox c in pnlSheetNames.Controls)
{
    if (c.Checked == true) 
    { 
        sheetNames.Add("something");
    } 
 }
 //  Display list in gridview
 gv1.DataSource = sheetNames;
 gv1.DataBind();

I put the value 'test' into my list just to make sure I can see it, and the 'test' value is displayed on the gridview, but none of the checkbox text values are making it into my list. I've been looking at blogs for an hour, and according to everything I've read, this should be working. Can anyone tell me where I'm going wrong?

One thing, when I press the button on my web form to do this, my list of checkboxes immediately disappears, I assume when the button posts back... could my panel be clearing itself on postback before my code runs? I don't know how to check for that.

Any help appreciated.




Aucun commentaire:

Enregistrer un commentaire