Read values of dynamically generated checkboxes during postback

E

epigram

I've got a page that has a Panel object that I am dynamically adding
CheckBox controls to. The number of CheckBox controls and the name of each
control is based on a database query. I would like to know how I can query
for all the CheckBox controls on the page during postback and check their
checked attribute without using the name of each checkbox. I want to do
this in a generic way so that I don't have to requery the db or save the
names of all the CheckBox controls somewhere to use during postback. For
CheckBox controls that are placed on the page during design time, this is
easy because I know the name. I'm just not sure how to do this for the
particular scenario I am describing here.

Thanks!
 
S

samuelrobertson

In the Panel codebehind or in whatever Control you are adding the
checkboxes *directly* to just iterate through the Control collection by
number. The index will correspond to exactly what order you added them
in, so you'll have to know that.

foreach(Control control in this.Controls)
{
if(control is CheckBox)
{
CheckBox checkBox = (CheckBox) control;
// here is your checkbox
}
}

something liket this anyway
 
E

epigram

I thought I could do this to, but it doesn't seem to be working. Maybe my
approach is wrong. I am doing exactly this in my page load method (in the
area of code that only executes if it IS a postback). The Controls
collection for my panel, that I added the checkboxes to in page load (not in
a post back), is empty. I thought the viewstate would rebuild the controls
and the panel's Controls collection would have many controls in it. Is this
the case because I'm dynamically adding CheckBox controls to the panel?

Thanks.
 
S

samuelrobertson

The Controls collection for my panel, that I added the checkboxes
to in page load (not in a post back)


Haha. Anyway, you need to add the checkboxes *all* the time, not just
if not postback.
 
S

samuelrobertson

Oh yes. Even if you do what I said, they won't have the right
'checked' values in them until the button click postback event happens.
Add them in the OnInit method and then you can get the right state in
PageLoad.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top