I have a code like this:
public static void ToUpperCase(params Control[] controls)
{
foreach (Control oControl in controls)
{
if (oControl is TextBox)
{
oControl.TextChanged += (sndr, evnt) =>
{
TextBox txtControl = sndr as TextBox;
int pos = txtControl.SelectionStart;
txtControl.Text = txtControl.Text.ToUpper();
txtControl.SelectionStart = pos;
};
}
else if (oControl is ComboBox)
{
oControl.TextChanged += (sndr, evnt) =>
{
ComboBox cmbControl = sndr as ComboBox;
int pos = cmbControl.SelectionStart;
cmbControl.Text = cmbControl.Text.ToUpper();
cmbControl.SelectionStart = pos;
};
}
else throw new NotImplementedException(oControl.GetType().DeclaringType.ToString() + " is not allowed.");
}
}
I want to limit the params Control[] controls
to accept only a TextBox
and a ComboBox
type.
My code is in C#, framework 4, build in VS2010Pro, the project is in WinForms.
Please help. Thanks in advance.
You can't- they don't have a good common ancestor.
What you can (and probably should) do is make two overloads of your method, which take parameters of each:
public static void ToUpperCase(params TextBox[] controls)
{
foreach (TextBox oControl in controls)
oControl.TextChanged += (sndr, evnt) =>
{
TextBox txtControl = sndr as TextBox ;
int pos = txtControl.SelectionStart;
txtControl.Text = txtControl.Text.ToUpper();
txtControl.SelectionStart = pos;
};
}
public static void ToUpperCase(params ComboBox[] controls)
{
foreach (ComboBoxControl oControl in controls)
oControl.TextChanged += (sndr, evnt) =>
{
ComboBox txtControl = sndr as ComboBox;
int pos = txtControl.SelectionStart;
txtControl.Text = txtControl.Text.ToUpper();
txtControl.SelectionStart = pos;
};
}
Normally you should use a common base class for TextBox or ComboBox but that is already Control. Also you cannot change the base classes of those.
The best I can come up with is to add a Debug.Assert to check the type. Something like:
foreach (var control in controls)
Debug.Assert((control is TextBox) || (control is ComboBox));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With