Hi All,
How to use validations for windows application with c#. I have kept "error provider" for two text box validation. It is showing error, But at the same time record also saving in to database.Once all the fields is field then only record will be save in to database. And how to add required validation for combo box?
Thanks and regards,
Murali.
[Updated Code]
Submit Button click -------
private void btnFamilysaveandnext_Click(object sender, EventArgs e)
{
txtAddress_Validated(this, e);
txtcity_Validated(this, e);
txtPincode_Validated(this, e);
SqlConnection con = new SqlConnection(strConn);
con.Open();
SqlCommand cmd = new SqlCommand("sp_rm_insert_basicfamily", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FamilyID", txtFamilyid.Text);
cmd.Parameters.AddWithValue("@HHID", txtHeadofhousehold.Text);
cmd.Parameters.AddWithValue("@Religion", cbxReligion.SelectedValue);
cmd.Parameters.AddWithValue("@Caste", cbxCaste.SelectedValue);
cmd.Parameters.AddWithValue("@HouseNo", txtHouseno.Text);
cmd.Parameters.AddWithValue("@Address1", txtAddress.Text);
cmd.Parameters.AddWithValue("@Village", txtcity.Text);
cmd.Parameters.AddWithValue("@State", cbxState.SelectedValue);
cmd.Parameters.AddWithValue("@District", cbxDistrict.SelectedValue);
cmd.Parameters.AddWithValue("@Mandal", cbxMandal.SelectedValue);
cmd.Parameters.AddWithValue("@Pincode", txtPincode.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Successfully Saved");
}
private void txtAddress_Validated(object sender, EventArgs e)
{
bool bTest = txtAddressValidate();
if (bTest == true)
{
this.errorProvider1.SetError(txtAddress, "This field must contain text");
}
else
{
this.errorProvider1.SetError(txtAddress, "");
}
}
private bool txtAddressValidate()
{
if (txtAddress.Text == string.Empty)
{
return true;
}
else
{
return false;
}
}
private void txtcity_Validated(object sender, EventArgs e)
{
bool bTest = txtcityStringIsValid();
if (bTest == true)
{
this.errorProvider1.SetError(txtcity, "Enter your City");
}
else
{
this.errorProvider1.SetError(txtcity, "");
}
}
private bool txtcityStringIsValid()
{
if (txtcity.Text == string.Empty)
{
return true;
}
else
{
return false;
}
}
private void txtPincode_Validated(object sender, EventArgs e)
{
bool bTest = txtPincodeStringIsValid();
if (bTest == true)
{
this.errorProvider1.SetError(txtPincode, "Please enter 6 Digits");
}
else
{
this.errorProvider1.SetError(txtPincode, "");
}
}
private bool txtPincodeStringIsValid()
{
char[] testArr = txtPincode.Text.ToCharArray();
bool testBool = false;
if (testArr.Length < 6)
{
testBool = true;
}
return testBool;
}
I have use the "validated" event for that.