Need to expose specific properties for controls in a collection

  • Thread starter Thread starter Stefan W via .NET 247
  • Start date Start date
S

Stefan W via .NET 247

I'm relatively new to C#, (I have to use it, now that I'veinherited someone else's projects). I'm looking for a way toiterate through the controls on a form; if the control is of acertain type, I want to set a property that is specific to thatcontrol type. The problem I'm having is that the "generic"Control object might not
contain the properties that I want to set.

Here's an example of what I'd like to try to do:

//loop through all controls on a form
foreach(Control ctrl in this.Controls)
{
//if control is a textbox
if(ctrl is TextBox)
{
//set a property that is specific to that control type
//If ctrl is a Textbox, set the ReadOnly property to True
ctrl.ReadOnly = true;
}
}

That is the general idea that I have; unfortunately, I'm notcertain that it's
possible to do this. Any help would be appreciated.

Thanks!
 
Stefan,

In this case, all you have to do is cast the instance of control to the
type specific instance, like so:

//loop through all controls on a form
foreach(Control ctrl in this.Controls)
{
//if control is a textbox
if(ctrl is TextBox)
{
//set a property that is specific to that control type
//If ctrl is a Textbox, set the ReadOnly property to True
((TextBox) ctrl).ReadOnly = true;
}
}

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

I'm relatively new to C#, (I have to use it, now that I've inherited someone
else's projects). I'm looking for a way to iterate through the controls on
a form; if the control is of a certain type, I want to set a property that
is specific to that control type. The problem I'm having is that the
"generic" Control object might not
contain the properties that I want to set.

Here's an example of what I'd like to try to do:

//loop through all controls on a form
foreach(Control ctrl in this.Controls)
{
//if control is a textbox
if(ctrl is TextBox)
{
//set a property that is specific to that control type
//If ctrl is a Textbox, set the ReadOnly property to True
ctrl.ReadOnly = true;
}
}

That is the general idea that I have; unfortunately, I'm not certain that
it's
possible to do this. Any help would be appreciated.

Thanks!
 
Back
Top