Add a label with the name ‘label1’, a textbox with the name ‘txtText’ and a button with the name ‘btnValidate’ as given in the above form. Also add error provider control to the form with the name ‘errorProvider’. Rename the Form as ‘FormTextBoxValidator’.
Then add this method to the FormTextBoxValidator.cs to validate the textbox.
private bool textBoxValidate()
{
errorProvider.Clear();
if (txtText.Text.Trim() == "")
{
errorProvider.SetError(txtText, "Text should be non empty");
return false;
}
return true;
}
Then to the click event of the ‘ btnValidate’ add the following code.
private void btnValidate_Click(object sender, EventArgs e)
{
if (textBoxValidate())
{
MessageBox.Show("Content validated!");
}
}
When you run the application, and click the validate button without entering a text to the textbox, it will provide an error as follows.
If you enter some text to the textbox, it will validate the textbox.