Pedro Ávila Pedro Ávila - 6 days ago 7
C# Question

Get specific controls a list of controls

I have a list of controls that get a

groupbox
, in which there
TextBox
,
ComboBox
,
CheckBox
.

When getting the list nececito differentiate and get the name of each control I tested with this code.

private void btnGuardar_Click(object sender, EventArgs e)
{
List<Control> lstControles =
new List<Control>(groupBox1.Controls.OfType<Control>().OrderBy(x => x.Name));

TextBoxUniversal txt = new TextBoxUniversal();
EntitySelectorCombo cbo = new EntitySelectorCombo();
CheckBox chk = new CheckBox();

foreach (var item in lstControles)
{
if(txt == item.Controls.OfType<TextBoxUniversal>())


if (cbo == item.Controls.OfType<EntitySelectorCombo>())

if (chk == item.Controls.OfType<CheckBox>())

}

Answer

You did it the wrong way (your code compares each object from list with newly instantiated object by reference, which always return a false result).

Try using is operator to check object type compatibility :

foreach (var item in lstControles)
{
     if(item is TextBoxUniversal)
        .......

     if (item is EntitySelectorCombo)
        .......

     if (item is CheckBox)
        .......
}
Comments