You cant use object-oriented approach to get the value, because they don't have common ancestor in inheritance tree from which you can fetch data. Solutions are so inelegant that you should just pass WebControl
and check type dynamically.
Pardon my C#:
(note that this is notepad code, I didn't run any of it so you may need some tweaks)
Solution 1: Get data directly from Request
Downside: Not very ASP.NET-ish. Does the job however.
public string GetTextValue<ResultType>(WebControl control, ResultType defaultValue)
{
// If you only wish data from form, and not questy string or cookies
// use Request.Form[control.UniqueId] instead
string value = Request[control.UniqueId];
return ConvertValue<ResultType>(value, defaultValue);
}
Solution 2: Check type dynamically
Downside: you have to provide handling for multiple control types
public string GetTextValue<ResultType>(WebControl control, ResultType defaultValue)
{
if (control is ITextControl)
return ConvertValue<ResultType>((ITextControl)control.Text, defaultValue);
else if (control is HiddenField)
return ConvertValue<ResultType>((HiddenField)control.Value, defaultValue);
else if (anothertype)
return ConvertValue<ResultType>(another_retrieval_method, defaultValue);
}
Solution 3: Use reflection
Downside: reflection can be tricky, doesn't look elegant, and can be slow on many invocations
public string GetTextValue<ResultType>(WebControl control, ResultType defaultValue)
{
// Get actual control type
Type controlType = control.GetType();
// Get the attribute which gives away value property
Attribute attr = controlType.GetCustomAttribute<ControlValuePropertyAttribute>();
if (attr == null)
throw new InvalidOperationException("Control must be decorated with ControlValuePropertyAttribute");
ControlValuePropertyAttribute valueAttr = (ControlValuePropertyAttribute)attr;
// Get property name holding the value
string propertyName = valueAttr.Name;
// Get PropertyInfo describing the property
PropertyInfo propertyInfo = controlType.GetProperty(propertyName);
// Get actual value from the control object
object val = propertyInfo.GetValue(control);
if (val == null)
val = "";
return ConvertValue<ResultType>(val, defaultValue);
}