2

I'm looping through the Controls collection of an asp:Panel, and I am not sure how to set Properties specific to some controls...

For example the Panel might contain a DropDownList, and I would like to be able to set and get the SelectedValue of this. Or it might contain a TextBox, and I would like to set and get the Text property.

I'm using this code to traverse:

foreach (Control control in panel.Controls)
{
    // ...
}

And since I get just a Base Control from this, it appears not to be able to get/set any of these properties as they are not defined for the Base Control.

So, what to do?

Thanks

henrik242
  • 366
  • 4
  • 11

3 Answers3

2

One possibility is to use the as operator:

foreach (Control control in Controls) {
    TextBox txt = control as TextBox;
    if (txt!=null) {
        txt.Text = "bla";
        ...
    }

    ComboBox cbo = control as ComboBox;
    if (cbo!=null) {
        cbo.SelectedItem = ...
        ...
    }

    ...
}

Note: If you have multiple controls of one type, you may use the Tag property to store additional information. While Tag is of type object, you also need the as operator here...

joe
  • 8,344
  • 9
  • 54
  • 80
  • 1
    Much better, would save one cast! – nunespascal Aug 06 '13 at 19:15
  • After researching "is", I agree that this is the best solution. http://stackoverflow.com/questions/686412/c-sharp-is-operator-performance – Garrison Neely Aug 06 '13 at 19:18
  • Would this not create a new control for each control in the collection? What I want is to access the properties of the actual controls in the Controls collection. – henrik242 Aug 06 '13 at 19:25
  • 1
    No, it would not do that. Its only a reference. – nunespascal Aug 06 '13 at 19:27
  • 1
    @user866173: No: `TextBox txt = control as TextBox` is the same as `TextBox txt = control is TextBox ? (TextBox)control : null`. So it's like "Test if it's of Type X" and if true, "Cast to Type X" else "return null". Please see the provided link. – joe Aug 06 '13 at 19:28
0

You could always check the type, and then cast it to that type.

foreach (Control control in Controls)
{
  if (control.GetType().Equals(typeof(DropDownList)))
  {
    ((DropDownList)control).Enabled = value;
  }
}
nunespascal
  • 17,584
  • 2
  • 43
  • 46
0

You should be able to use the is operator like so:

if(control is DropDownList)
{
    // Cast control as DDL and do your work
}
Garrison Neely
  • 3,238
  • 3
  • 27
  • 39