Reputation: 37
Is it possible in C# to alert user (with MessageBox) and return;
if he's inserting same values to columns with unique constraint? I have unique in LastName, FirstName, and MiddleInitial.
String command = "INSERT IGNORE INTO studentstbl (LastName, FirstName, MiddleInitial, Address, Age, Birthday, Gender, Guardian, ContactNumber, Year, IsEnrolled) VALUES (@lastname, @firstname, @middleinitial, @address, @age, @birthday, @gender, @guardian, @contactnumber, @year, 0);";
MySqlCommand cmd = new MySqlCommand(command, conn);
cmd.Parameters.AddWithValue("@lastname", lastnametxt.Text);
cmd.Parameters.AddWithValue("@firstname", firstnametxt.Text);
cmd.Parameters.AddWithValue("@middleinitial", middleitxt.Text);
cmd.Parameters.AddWithValue("@address", addresstxt.Text);
cmd.Parameters.AddWithValue("@age", agetxt.Text);
cmd.Parameters.AddWithValue("@birthday", birthdaypicker.Text);
cmd.Parameters.AddWithValue("@gender", gendercmb.Text);
cmd.Parameters.AddWithValue("@guardian", guardiantxt.Text);
cmd.Parameters.AddWithValue("@contactnumber", contactnumtxt.Text);
cmd.Parameters.AddWithValue("@year", yearcmb.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
reset();
MessageBox.Show("Student successfully registered! You can now proceed to Payment to enroll student.");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Upvotes: 3
Views: 213
Reputation: 5811
You either have to run a query to check first, or take off the "IGNORE" from you query, so you can catch the error. If you take the "IGNORE" off, you can catch the more specific MySqlException and check the error number. 1062 means there was a unique key violation. The MySQL documentation has a full list of the error numbers. Something like this:
catch (MySql.Data.MySqlClient.MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
case 1062:
MessageBox.Show("Name already exists");
}
}
finally
{
//Since you've taken the ignore off you can run whatever you wanted to run here.
}
Upvotes: 2