我想允許用戶添加「類別」。添加到組合框並檢查重複項(C#)
但是,在類別實際添加之前,我想確保它不是重複的。
這裏是我的代碼:
//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();
}
}
}
此代碼不能正常工作,而不管其重複的或者不是它增加了用戶輸入的類別。
我也嘗試了foreach
循環下面的代碼:
foreach (var item in catcombobox.Items)
,仍然不起作用。
我該如何讓它起作用?
SOLUTION:
if (dvrow.Row["Category"].Equals(addcattxt.Text))
{
MessageBox.Show("This category already exists.",
"Invalid Operation: Duplicate Data",
MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
你爲什麼插入到數據庫中的foreach dvrow不匹配?也許你打算把這個放在foreach之外? – ryanyuyu
@ryanyuyu耶。我做了更改,但結果仍然相同。 – John