Scan Through All DropDownList on WebForm

  • Thread starter Thread starter crjunk
  • Start date Start date
C

crjunk

Hi everyone,

I'm trying to write a procedure in that will loop through all the
controls on a form. If the control is a DropDownList, then I want to
build a query based on the DropDownList's selected value. I'm not
very familiar with C#. I come from a VB.NET background.

Can someone tell me what I'm doing wrong ?

This is what I've tried to write:

DropDownList ctrlNameDropDown = new DropDownList();

foreach (Control ctrl in Page.FindControl("frmMain").Controls)
{
if (ctrl is DropDownList)
{
ctrlNameDropDown = (DropDownList)Page.FindControl(ctrl.ID);
// Write something to see if code is working.
Response.Write
(ctrlNameDropDown.SelectedItem.Text);
}
}

Thanks,
crjunk
 
Hi everyone,

I'm trying to write a procedure in that will loop through all the
controls on a form. If the control is a DropDownList, then I want to
build a query based on the DropDownList's selected value.  I'm not
very familiar with C#. I come from a VB.NET background.

Can someone tell me what I'm doing wrong ?

This is what I've tried to write:

DropDownList ctrlNameDropDown = new DropDownList();

foreach (Control ctrl in Page.FindControl("frmMain").Controls)
{
     if (ctrl is DropDownList)
     {
          ctrlNameDropDown = (DropDownList)Page.FindControl(ctrl.ID);
          // Write something to see if code is working.
          Response.Write
(ctrlNameDropDown.SelectedItem.Text);
     }

}

Thanks,
crjunk

You are over-using the FindControl method. If the page form has an id
of 'frmMain' then it is directly accessible in code as frmMain.
Furthermore there is no need for FindControl in the body of the loop
because 'ctrl' is already there as a Control object. However you need
to do a cast before handling ctrl as a DropDownList.

Try this:

foreach(Control ctrl in frmMain.Controls)
if(ctrl is DropDownList)
{
DropDownList ctrlDropDown = (DropDownList)ctrl;
Response.Write(ctrlDropDown.SelectedValue);
}
 
You are over-using the FindControl method. If the page form has an id
of 'frmMain' then it is directly accessible in code as frmMain.
Furthermore there is no need for FindControl in the body of the loop
because 'ctrl' is already there as a Control object. However you need
to do a cast before handling ctrl as a DropDownList.

Try this:

foreach(Control ctrl in frmMain.Controls)
if(ctrl is DropDownList)
{
      DropDownList ctrlDropDown = (DropDownList)ctrl;
      Response.Write(ctrlDropDown.SelectedValue);

}

Thanks for your help! This helped me out a lot.

Here is my final solution.

{
foreach (Control ctrl in this.Controls )
if (ctrl is DropDownList)
{
DropDownList ctrlDropDown = (DropDownList)ctrl;
Response.Write(ctrlDropDown.SelectedValue);
}
}

C.R. Junk
 
Back
Top