1

I'm trying to locate a checkbox on my webform, but am not able to? It's always set to NULL? I have tried different approaches (the i is set via a FOR loop, I'm using a Masterpage as well):

CheckBox cb = (CheckBox)this.FindControl("ctl00_ContentPlaceHolder1_sa" + i.ToString());

CheckBox cb = (CheckBox)Page.FindControl("ctl00_ContentPlaceHolder1_sa" + i.ToString());

CheckBox cb = (CheckBox)Parent.FindControl("ctl00_ContentPlaceHolder1_sa" + i.ToString());

... as well as...

CheckBox cb = (CheckBox)this.FindControl("sa" + i.ToString());

CheckBox cb = (CheckBox)Page.FindControl("sa" + i.ToString());

CheckBox cb = (CheckBox)Parent.FindControl("sa" + i.ToString());

Any ideas?

TaW
  • 53,122
  • 8
  • 69
  • 111
Robert Benedetto
  • 1,590
  • 2
  • 29
  • 52

3 Answers3

1

Findcontrol works with the id, not the clientside generated id (as your first code block looks like).

Use Findcontrol on the parent object (not always necessary if I'm correct). If the checkbox is on the page body, use Page.FindControl, or this.FindControl. When it's in a listview for example, use it in the proper event.

Erik
  • 119
  • 6
1

You can try this code:

foreach ( Control c in Panel1.Controls )
{
    CheckBox cb = c as CheckBox;
    if(cb!=null)
    {

    }
}

Here Panel1 contains all the checkbox..thank you.

Linda Manu
  • 43
  • 10
1

I placed the checkboxes inside a panel, and was able to access them with Panel1.FindControl as per @linuser.

Feels like a quickfix but it works.

Robert Benedetto
  • 1,590
  • 2
  • 29
  • 52