There isn't such common Value
property in Control
class.
You should use some if/else or switch/case or a dictionary approach to get the value from the control. Because you know what property you need. The control just provides properties.
For example for a ComboBox
, what is the value? Is it SelectedItem
, SelectedIndex
, SelectedValue
, Text
? It's usage/opinion based.
The nearest thing to what you are looking for, is relying on DefaultProperty
attribute of controls to get the value from that property using relfection. For example, having this method:
public object GetDefaultPropertyValue(Control c)
{
var defaultPropertyAttribute = c.GetType().GetCustomAttributes(true)
.OfType<DefaultPropertyAttribute>().FirstOrDefault();
var defaultProperty = defaultPropertyAttribute.Name;
return c.GetType().GetProperty(defaultProperty).GetValue(c);
}
You can get values this way:
var controls = new List<Control> {
new Button() { Text = "button1" },
new NumericUpDown() { Value = 5 },
new TextBox() { Text = "some text" },
new CheckBox() { Checked = true }
};
var values = controls.Select(x => GetDefaultPropertyValue(x)).ToList();