How to check if a MaskedTextBox is empty from a user input?
Solution 1
You can simply use:
maskedTextBox1.MaskCompleted
Or
maskedTextBox1.MaskFull
properties to check if user has entered the complete mask input or not.
Solution 2
I know this is old but I would first remove the mask and then check the text like a normal textbox.
maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
//...Perform normal textbox validation
Solution 3
I just faced this problem. I Needed the Masked Value, but also needed send empty string if the user didn't introduced any data in one single step.
I discovered the property MaskedTextProvider.ToDisplayString so I use the MaskedTextbox with:
maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
BUT I always read the text from:
maskedTextBox.MaskedTextProvider.ToDisplayString()
This way, if the user has not introduced text in the control Text property will be empty:
maskedTextBox.Text == string.Empty
And when you detect the string is not empty you can use the full text including literals for example:
DoSomething((maskedTextBox.Text == string.Empty) ? maskedTextBox.Text: maskedTextBox.MaskedTextProvider.ToDisplayString());
or
DoSomething((maskedTextBox.Text == string.Empty) ? string.Empty: maskedTextBox.MaskedTextProvider.ToDisplayString());
Solution 4
If you set the property maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals then the TypeValidationCompleted event validation will not work. To test if the short date maskedtextbox is empty you could just use:
if (maskedTextBox1.Text == " / /")
{
...;
}
Solution 5
Did you try trim.
if(string.IsNullOrEmpty(maskedTextBox.Text.Trim())
Muhammed Salah
Updated on June 22, 2021Comments
-
Muhammed Salah almost 3 years
I'm using a
MaskedTextBox
, with the following short dateMask
: "00/00/0000".
My problem is that I wanna know when the control is empty:if (string.IsNullOrEmpty(maskedTextBox1.Text)) { DataTable dt = function.ViewOrders(Functions.GetEid); dataGridView2.DataSource = dt; }
It's not working, when
maskedTextBox1
looks empty (and I'm sure it is), theif
statement doesn't detect that it isnull
orEmpty
.