Data entered by user, should be valid and properly formatted, Otherwise a lot of resources could be wasted in fixing the problems that could be arise due to incorrect data format. Data should be properly checked according to the input criteria. Windows forms provides some ways to validate input in your application.
Just add a MaskedTextBox control and look out the mask property. There are approx. 9 predefined masks such as Phone number, zip code, Numeric digits etc. as in following screenshot:
There is no mask for mobile no in the above masks, so we have to create a new mask. Use the last mask i.e. custom mask and insert ten zero’s in the mask textbox just below the list of mask because mobile no is of ten digits, and our new mask has been created.
Masked TextBox Validation
We often requires some data like contact number in a well-defined format and also correct no of digits. This problem can easily be solved by using MaskedTextBox in windows forms. MaskedTextBox displays some formats to the user. If user types a wrong entry then this textbox automatically reject that input.Just add a MaskedTextBox control and look out the mask property. There are approx. 9 predefined masks such as Phone number, zip code, Numeric digits etc. as in following screenshot:
There is no mask for mobile no in the above masks, so we have to create a new mask. Use the last mask i.e. custom mask and insert ten zero’s in the mask textbox just below the list of mask because mobile no is of ten digits, and our new mask has been created.
Event-Driven Validation
Each input control has a Validating event that occur whenever the control requires data validation. Validating event enables you to prevent from shifting focus from the control being validated to another control until validation has been completed.
To check whether the textbox is blank or not, we will simply check this by using the following line of codes in validating event of textbox in C# language.
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text == string.Empty)
{
MessageBox.Show("Textbox is empty");
}
}
Just like above code we can validate any other control using some lines of code. There is an argument e of type CancelEventArgs, which can be used to cancel the validating event if required input has been entered by user.
As in above screenshot if the textbox left empty by the user then a message has been displayed written above. This message can be displayed by any of the message box, status strip etc.
Tidak ada komentar:
Posting Komentar