Search code examples
castingcomboboxforeachcontrolsstackpanel

Loop through stackPanel.children genericaly


In code I am dynamically adding controls (e.g. TextBox, ComboBox, Label, etc) that I would like to now loop through and get the values from each applicable (e.g. not Labels) control that a user inputted data for.

        foreach (Control control in EditForm.Children)
        {
            values = new List<string>();
            fieldName = control.Name;

            if (control is ComboBox)
            {
                ComboBox cmb = control as ComboBox;

                string value = cmb.SelectedValue.ToString();
            }
         }

The problem is that I get an error during runtime of

Unable to cast object of type 'System.Windows.Controls.TextBlock' to type 'System.Windows.Controls.Control'.

Is there a more generic class I should be using instead of 'Control'? How can I loop through each control and have access to the needed values (includes the control's Name)


Solution

  • "UIElement" is most likely a safe choice.

    If you're only interested elements of a specific type, you can also consider using Linq to filter out elements by class type (don't forget to include a "using System.Linq" directive):

    foreach (ComboBox combo in EditForm.Children.OfType<ComboBox>())
    {
       //...
    }