简体   繁体   中英

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;
        }
    }

I believe the problem is that Text is also returning the mask characters, so although the user has not set any text, there is still the text from those characters. (You can confirm this by adding a breakpoint and checking Text )

You should be able to get only the user inputted part of the text by changing the TextMaskFormat property before the check, and then setting it back afterwards.

EDIT: Unfortunately, changing the TextMaskFormat seems to also fire the TextChanged event, which can cause a stack overflow if not handled carefully. This can be avoided by having a flag to suppress the event code, something like this:

bool suppressTextChanged = false;
private void mtbCNIC_TextChanged(object sender, EventArgs e)
{
    if (suppressTextChanged)
        return;

    suppressTextChanged = true;
    mtbCNIC.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
    btnSave.Enabled = mtbCNIC.Text != string.Empty;
    mtbCNIC.TextMaskFormat = MaskFormat.IncludeLiterals;
    suppressTextChanged = false;
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM