MaskedTextBox mtxtBox = ctrl as MaskedTextBox;
TextBox txtBox = ctrl as TextBox;
ComboBox cmb = ctrl as ComboBox;
mtxtBox.TextChanged += new EventHandler(this.TextWasChanged);
txtBox.TextChanged += new EventHandler(this.TextWasChanged);
cmb.SelectedIndexChanged += new EventHandler(this.TextWasChanged);
A control will not be both a
MaskedTextBox
, a
TextBox
and a
ComboBox
at the same time. Two of those variables will always be
null
, so you'll get a
NullReferenceException
when you try to add a handler to the relevant "changed" event.
Change your code to check for
null
before trying to add the handler:
MaskedTextBox mtxtBox = ctrl as MaskedTextBox;
if (mtxtBox != null)
{
mtxtBox.TextChanged += TextWasChanged;
}
else
{
TextBox txtBox = ctrl as TextBox;
if (txtBox != null)
{
txtBox.TextChanged += TextWasChanged;
}
else
{
ComboBox cmb = ctrl as ComboBox;
if (cmb != null)
{
cmb.SelectedIndexChanged += TextWasChanged;
}
}
}
NB: For future reference,
"it doesn't work" is not a good description of the problem. Always include the full details of any exception your code is throwing.