How to validate if an entry exists, and if not, add it?
Please see my code below. I'd like to validate if an entry exists and if
not, add it. How can I do that?
private void btnAdd_Click(object sender, EventArgs e)
{
string conString =
"SERVER=localhost;DATABASE=restosystem;UID=root;PASSWORD=qwerty;";
MySqlConnection conn = new MySqlConnection(conString);
MySqlConnection con = new MySqlConnection(conString);
try
{
MySqlCommand command1 = new MySqlCommand("Select * from
tblcategories where CategName = '" + txtCategName.Text + "'",
conn);
conn.Open();
MySqlDataReader DR1 = command1.ExecuteReader();
if (DR1.Read())
{
MessageBox.Show("Category Already Exist!", "Add Category",
MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCategName.Text = "";
}
else
{
MySqlCommand command = new MySqlCommand("Insert into
tblcategories(CategID,CategName) VALUES ('"+ txtCatID.Text
+"','" + txtCategName.Text + "')", conn);
conn.Open();
command.ExecuteNonQuery();
MessageBox.Show(" Successfully Added", "Add Category",
MessageBoxButtons.OK, MessageBoxIcon.Information);
lvCateg.Items.Clear();
CreateID();
categlist();
txtCategName.Text = "";
}
conn.Close();
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
No comments:
Post a Comment