Looping through controls error?? please

A

Annie

hello guys,

I am getting the following error:
Exception Details: System.NullReferenceException: Object reference not set
to an instance of an object.

What i am trying to do is to loop through all of the controls on the page
and if they are Checkboxes and then see if the they are
checked then do something ...

private void Button1_Click(object sender, System.EventArgs e)

{

CheckBox chk=null;

foreach (Control ctl in this.Controls)

{


if (ctl is CheckBox)

chk = (CheckBox) ctl;

if (chk.Checked)

{

Response.Write(chk.Text);

}

}

}

i don't know what is wrong here???
 
A

Annie

It compiles fine. but when i press the button it raises the error.

Line 64: if (chk.Checked)

Anyways, how would you loop though all your controls in a page and check for
some types eg CheckBox or Button etc

Ta
 
P

Praveen

Hi,
U have used correctly....but one small mistake...u dint use "{ }" ie
brackets after the statement if(ctl is CheckBox)....

but u will not get just with this.Controls in for loop..
the whole code should look like..

foreach(Control ctl in this.Controls[1].Controls){
if (ctl is CheckBox){
ch = (CheckBox)ctl;
Response.Write(ch.Text + " "); .......include whatever u want
}
}
Controls[1] refers to the form
It will fetch all the check boxes placed (directly) on the form.
....if u have placed check boxes in any data grid or in a data
list...then u need to use Recursion for traversing throught the control
hierarchy.
hope it helps,

Praveen P.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top