given:
protected void SearchedValues2(object sender, EventArgs e)
{
if (sender is CheckBox)
{
CheckBox cb1 = (CheckBox)sender;
controlValues.Add(KeyValuePair<string, string>(cb1.ID,
cb1.Text));
}
else if (sender is DropDownList)
{
DropDownList ddl1 = (DropDownList)sender;
controlValues.Add(KeyValuePair<string, string>(ddl1.ID,
ddl1.Text));
}
else if (sender is TextBox)
{
TextBox txb1 = (TextBox)sender;
controlValues.Add(KeyValuePair<string, string>(txb1.ID,
txb1.Text));
}
}
question:
if i knew i only wanted the id and the value of the control could i shorten
the code somehow?
thanks,
rodchar
second create new TextBox and DropDownList and CheckBox Controles that
inherit their ancestors and implement the new interface:
public class InterfacedTextBox: TextBox, ITextAndID
{}
public class NewCheckBox: CheckBox. ITextAndID
{}
Mind that these new classes do not need any code between the brackets.
Finally replace the TextBox, CheckBox and DropDownList on your form by their
Interfaced counterparts. The compiler will complain until you have got this
right.
Now you method can be shortened to:
protected void SearchedValues2(object sender, EventArgs e)
{
if (sender is ITextAndID)
{
var cb1 = (ITextAndID)sender;
controlValues.Add(KeyValuePair<string, string>(cb1.ID,
cb1.Text));
}
--
J.
Control is the base of all of your objects that you test. You can get
Control.ID, but, Control doesn't have a Text property so I don't think it
really helps you.
--
Mike
For completeness, there's one way of accessing properties in a generic
fashion that (almost) always works, and that's data binding.
DataBinder.Eval(sender, "Text") will get you the text, but since it uses
reflection and can return only strings, this is none too efficient. Still,
this is not a loop, so it wouldn't matter much.
--
J.
In windowforms not in asp.net
...or you can be more "generic"
while it seems slightly more complex, it does not impact on a
perfrmance:
public abstract class BaseControl : ITextAndID
{
public abstract string Text
{ get; }
public abstract string ID
{ get; }
}
public abstract class
ControlWrapper(T, U):
BaseControl,
ITextAndID
where T : ControlWrapper(T, U)
{
private readonly U _c;
protected ControlWrapper(U control){ _c = control; }
}
public T Control
{ get { return _c; } }
}
public class TextBoxWrapper : ControlWrapper(TextBoxWrapper, TextBox)
{
public TextBoxWrapper(TextBox text) : base(text) { }
public override string Text
{
return Control.Text;
}
public override string ID
{
return Control.ID;
}
}
So, in code you can use BaseControl class in methods
AND use
BaseControl's .Control object for other stuff;
Wile I'd prefer to do all job in derived from BaseClass classes (which
makes Control property protected), sometimes it needs to access
original wrapped object