[2.0] Validating Text boxes
I am working on a Windows application in C#
I have two text boxes, to be validated with (txtFirstName and txtLastName)
Please could someone give me the syntax to use txtFirstName_Validating()
TO achieve the validation.
I have put the validation code inside the Button click event.
Please could you give me the best approach to validate the text boxes.
Thank you,
-----------------------------------------------------------------------
private void txtFirstName_Validating(object sender, CancelEventArgs e)
{
if (string.IsNullOrEmpty(txtFirstName.Text))
{
MessageBox.Show("First Name required!");
}
}
private void btnLookUp_Click(object sender, EventArgs e)
{
if ((txtFirstName.Text == string.Empty) || (txtLastName.Text ==
string.Empty))
{
MessageBox.Show("Please enter the Name..");
}
}
Re: [2.0] Validating Text boxes
There's no point using IsNullOrEmpty because the Text property of a control can NEVER return a null reference. You only have to check for an empty string. You would use something like this in the Validating event handler:
Code:
if (this.txtFirstName.Text == string.Empty)
{
e.Cancel = true; //This line prevents the control losing focus.
MessageBox.Show("Please enter a value for First Name.");
}
Note that this does not stop the user entering whitespace only. I would also recommend using code like this in the Leave event:
Code:
//Remove leading and trailing whitespace.
this.txtFirstName.Text = this.txtFirstName.Text.Trim();
The Leave event is raised before the Validating event so this will turn a whitespace only value into an empty string before validating.