Question

I have a Winforms application that dynamically instantiates external form objects for use in a configuration UI. Each dynamically-instantiated form is placed in a TabPage.

I would like to create a property that will accept a Dictionary or Key/Value list, and populate the form with those values, matching up the value of the control with the value of the Key in the dictionary. Conversely, the property will also return a Key/Value list that corresponds to the values of the controls in the Winform.

Is this a simple binding problem, or do I need to write custom code? What would that code look like?

In the past, I have accomplished this by writing a DTO class, using XML serialization and deserialization to persist the class's data, and hooking up the form fields to the DTO object's fields. The problem is, since the form is dynamically instantiated from an external DLL, there's no way to "reference" this DTO class statically, so I'm looking for a more dynamic approach.

Was it helpful?

Solution

Turned out to be easier than I thought.

public Dictionary<string, string> Values
{
    get
    {
        var values = new Dictionary<string, string>();
        foreach (var control in Controls)
        {
            switch(control.GetType().Name) 
            {
                case "TextBox" : 
                    var textBox = (TextBox)control;
                    values.Add(textBox.Name, textBox.Text);
                    break;
                case "ComboBox":
                    var comboBox = (ComboBox)control;
                    values.Add(comboBox.Name, comboBox.SelectedItem.ToString());
                    break;
                case "CheckBox":
                    var checkBox = (CheckBox)control;
                    values.Add(checkBox.Name, checkBox.Checked.ToString());
                    break;

                // TODO: Add additional cases to support other control types
            }
        }
        return values;
    }
    set
    {
        foreach (var control in Controls)
        {
            switch (control.GetType().Name)
            {
                case "TextBox":
                    var textBox = (TextBox)control;
                    textBox.Text = value[textBox.Name];
                    break;
                case "ComboBox":
                    var comboBox = (ComboBox)control;
                    comboBox.SelectedItem = value[comboBox.Name];
                    break;
                case "CheckBox":
                    var checkBox = (CheckBox)control;
                    checkBox.Checked = bool.Parse(value[checkBox.Name]);
                    break;

                // TODO: Add additional cases to support other control types
            }
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top