2015-04-30 26 views
0

我想允許用戶添加「類別」。添加到組合框並檢查重複項(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; 
} 
+0

你爲什麼插入到數據庫中的foreach dvrow不匹配?也許你打算把這個放在foreach之外? – ryanyuyu

+0

@ryanyuyu耶。我做了更改,但結果仍然相同。 – John

回答

3

我覺得你的代碼是不工作,因爲DataRowView.ToString()返回對象的表示。你綁定哪一行的哪一行?你的檢查應該看起來可能更像:

if (dvRow.Row["Name"].Equals(addcattxt.Text)) ... 
+0

你能否詳細說明爲什麼'.Equals'比較字符串首選? –

+0

@ la-yumba是的,我試過使用'.Equals'(這是我的第一選擇)。您的代碼建議工作。我最初並沒有把它在執行檢查時提到的行名稱。我已經在我的問題中發佈瞭解決方案。 – John

+0

我也質疑你對第一點的理由;它可能適用於Java,但不適用於C#。看到[這個答案](http://stackoverflow.com/a/1659107/1378739) – Setsu

0

我覺得你的代碼將複製到數據庫中,因爲你沒有跳過部分,將其添加到數據庫中,如果你打一個副本。

如果它是不明確的,試試這個在您的代碼:

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;//<----- yeah jeff right no break here to 
    } 
    else 
    { 
     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(); 
     } 
    } 
} 

我希望能解決您的probem!祝你好運! :)

+1

if語句中的中斷應該導致它離開foreach循環並且永遠不會運行插入,即使沒有'else'。 –