This is well supported in Winforms. Use the Validating event to check the record, the ErrorProvider component to report an error. Example event handler:
private void textBox1_Validating(object sender, CancelEventArgs e) { int hour; e.Cancel = true; if (textBox1.Text.Length == 0) errorProvider1.SetError(textBox1, "Can't be empty"); else if (!int.TryParse(textBox1.Text, out hour)) errorProvider1.SetError(textBox1, "Not a number"); else if (hour < 1) errorProvider1.SetError(textBox1, "Hour too small"); else if (hour > 24) errorProvider1.SetError(textBox1, "Hour too large"); else { e.Cancel = false; errorProvider1.SetError(textBox1, ""); } }
Then you just need to check if all entries were satisfactory. Use the ValidateChildren () method in the OK Button Event Handler dialog box:
private void OKButton_Click(object sender, EventArgs e) { if (ValidateChildren()) this.DialogResult = DialogResult.OK; }
source share