I am validating user inputs using the above-mentioned functionality.
but when i press the ok / insert button this this.ValidateChildren(ValidationConstraints.Enabled)always return true.
below is my code. Kindly help . I am new to c# and dotnet.
private void textBox2_Validating(object sender, CancelEventArgs e)
{
bool cancel = false;
int number = -1;
if (int.TryParse(this.textBox2.Text, out number))
{
if (number>0 && number<100)
{
//This control passes validation.
cancel = false;
}
else
{
//This control has failed validation: number is not in the correct format
cancel = true;
this.errorProvider1.SetError(this.textBox2, "You must provide a number wit the format 11ddd!");
}
}
else
{
//This control has failed validation: text box is not a number
cancel = true;
this.errorProvider1.SetError(this.textBox2, "You must provide a valid number!");
}
e.Cancel=cancel;
}
private void textBox2_Validated(object sender, EventArgs e)
{
//Control has validated, clear any error message.
this.errorProvider1.SetError(this.textBox2, string.Empty);
}
private void button2_Click(object sender, EventArgs e)
{
if (this.ValidateChildren(ValidationConstraints.Enabled))
// if (validateOfficeId())
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=mOICISTAFF12;Integrated Security=True");
SqlCommand com;
con.Open();
com = new SqlCommand("INSERT INTO offices VALUES('" + textBox2.Text.Trim() + "','" + textBox3.Text.Trim() + "','" + textBox4.Text.Trim() + "','" + textBox5.Text.Trim() + "','" + textBox6.Text.Trim() + "','" + textBox7.Text.Trim() + "')", con);
com.ExecuteNonQuery();
//MessageBox.Show("i am in the validatechildren");
textBox2.Text = string.Empty;
textBox3.Text = string.Empty;
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
textBox6.Text = string.Empty;
textBox7.Text = string.Empty;
}
else
{
MessageBox.Show("there are invalid controls on the form");
Form1_Load( sender, e);
}