Thursday, March 22, 2012

Looping through controls error? please

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?Hi,
Could you tell - what code line results in exception ?
Kalpesh
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
"Kalpesh" <shahkalpesh@.gmail.com> wrote in message
news:1128348288.782194.122790@.o13g2000cwo.googlegroups.com...
> Hi,
> Could you tell - what code line results in exception ?
> Kalpesh
>
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.
Thanks Paraveen!
Very nice code
all the bests!
"Praveen" <praveen.pvs@.gmail.com> wrote in message
news:1128431641.724518.229280@.g43g2000cwa.googlegroups.com...
> 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.
>

0 comments:

Post a Comment