I have a program which adds values to a database from textboxes.
I need to provide a way through which if the value added is not unique, it should return an error message. But my current code is unable to do that. Even if the value is not unique, it is saving the data in the database.
Below is my code.
try
{
if (runningExperimentToolStripMenuItem.Enabled == true && newExperimentToolStripMenuItem.Enabled == true)
{
MessageBox.Show("Select experiment type (under menu item 'File') first, Running or New.", "Experiment Type Required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
if (sqlconf2.State == ConnectionState.Closed)
sqlconf2.Open();
//after connection is open, using following "if" code to check uniqueness of Step
string query = "Select * from ExpData where 'Animal ID' = '" + textBox5.Text.Trim() + "' and Step = '" + comboBox2.Text.Trim() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlconf2);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count > 0)
{
MessageBox.Show("This step has already been executed for the chosen animal ID. Please recheck. \n'Step' requires a numeric value from the drop down list. ", "Step Already Executed.", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation);
}
else
{//code to add data into database
}
}
sqlconf2.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Message");
MessageBox.Show("If problem persists, check trouble shooting options in user manual or on our website.", "Trouble Shooting.", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
datadisplay();
}