I want to allow the user to add a 'Category'.
However, before the Category is actually added, I want to make sure that it's not a duplicate.
Here is my code:
//ADD CATEGORY
private void addcat_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(addcattxt.Text))
{
MessageBox.Show("You must enter a valid category.",
"Invalid Operation: Data Missing",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
foreach (DataRowView dvrow in catcombobox.Items)
{
if (dvrow.ToString() == addcattxt.Text)
{
MessageBox.Show("This category already exists.",
"Invalid Operation: Duplicate Data",
MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
var query = "INSERT INTO category_table (Category) VALUES(@cat);";
using (var sqlcmd = new SqlCommand(query, sqlconnection))
{
sqlcmd.Parameters.AddWithValue("@cat", this.addcattxt.Text);
sqlcmd.ExecuteNonQuery();
}
this.DialogResult = DialogResult.OK;
this.Close();
}
}
}
This code does not work, and it adds the Category entered by the user, regardless of whether its a duplicate or not.
I've also tried the following code for the foreach
loop:
foreach (var item in catcombobox.Items)
, and still doesn't work.
How do I get it to work?
SOLUTION:
if (dvrow.Row["Category"].Equals(addcattxt.Text))
{
MessageBox.Show("This category already exists.",
"Invalid Operation: Duplicate Data",
MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}