I have a method that has a Control
parameter. I want to get the value of the control. So if it is a TextBox
get the value of the Text
property; if it is a NumericUpDown
get the value of the Value
property and so on.
The problem is that I cannot write something like this:
Method(Control control)
{
control.Text;
}
or
Method(Control control)
{
control.Value;
}
Because there is no guarantee that the control has one of these properties, and what is its name if it does have it. Is there a way to do something like that?
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.