tags:

views:

49

answers:

4

Hi everybody,

My problem is that, i want to count the controls on a page and then get their types, if there are textboxes, checkboxes or comboboxes, then make them enable or disable? Is there any example on the net?

Thanks

+4  A: 

This would be an expensive operation as you would have to recursively walk the control collection of the page checking each control. Perhaps you are not aware that ASP.NET cascades the Disabled property from parent to child? In other words if you set a parent control as disabled all child input controls will be disabled as well.

Edit: If you really want to do it this way then this is the best way to do it:

protected override void OnPreRender(EventArgs e)
{
 base.OnPreRender(e);

 int count = 0;

 this.disableControls(this, ref count);
}

void disableControls(Control control, ref int count)
{
    foreach (Control c in control.Controls)
    {
     WebControl wc = c as WebControl;

     if (wc != null)
     {
      count++;
      wc.Enabled = false;    
     }

     this.disableControls(c, ref count);
    }
}
Andrew Hare
A: 

You could use a method like:

public int CountControls(Control top)
{
    int cnt = 1;
    foreach (Control c in top.Controls)
        cnt += CountControls(c);
    return cnt;
}

But as Andrew said, it would be expensive.

Joel Potter
A: 
private void ChangeControlStatus(ControlCollection col, bool status)
 {
    foreach (Control ctrl in col)
        ChangeControlStatus(ctrl.Controls, status)

          if (ctrl is TextBox)

            ((TextBox)ctrl).Enabled = status;

          else if (ctrl is Button)

            ((Button)ctrl).Enabled = status;

          else if (ctrl is RadioButton)

            ((RadioButton)ctrl).Enabled = status;

          else if (ctrl is ImageButton)

            ((ImageButton)ctrl).Enabled = status;

          else if (ctrl is CheckBox)

            ((CheckBox)ctrl).Enabled = status;

          else if (ctrl is DropDownList)

            ((DropDownList)ctrl).Enabled = status; 

       else if (ctrl is HyperLink)

        ((HyperLink)ctrl).Enabled = status; 

 }
Glennular
Control has the Enabled property on it, you don't need to case each one... You could put the required types in an array and check the type instead. May be a little slower, but way more maintainable (should you need to change the control types it operates on).
Kieron
The requirement in the question was to "get their types", i agree it is not needed for Enabled but there might be other actions needed to be taken for specific types.
Glennular
A: 

Glennular,

This method is worked very fine, thanks for the replt

mehmetserif
You should put responses to answers in comments. Helps keep things clean. ;)
Joel Potter