kh aafi kh aafi - 24 days ago 8
C# Question

How to Enable/Disable Button on MaskedTextBox?

I have a maskedTextBox and a Save button. Now i want to enable Save button if user enter something and disable if the maskedTextBox is empty. I have done that for textBoxes on a textChanged Event of a textbox and work properly but i am not able to do that on a masked TextBox textChanged Event. Here is my code. Please help

private void mtbCNIC_TextChanged(object sender, EventArgs e)
{
if (mtbCNIC.Text == "")
{

btnSave.Enabled = false;
}
else
{

btnSave.Enabled = true;
}
}

Answer

In general, checking if text has value is not such useful, you need to have a valid input to enable the button. I prefer to rely on:

this.button1.Enabled = this.maskedTextBox1.MaskCompleted;

Mask is 00000-0000000-0

For such a specific mask you can simply Simply exclude - and _ from text and check for length:

var str = this.maskedTextBox1.MaskedTextProvider.ToDisplayString();
this.button1.Enabled = str.Replace("-", "").Replace("_", "").Length > 0;