2017-07-26 94 views
0

上週我問了同樣的問題,最終得到了解決我的問題的方法,這要感謝用戶@Aaron。然而,我再次問,因爲代碼在一個項目中完全工作,但在幾乎完全相同的條件下(即,列數/行數,變量類型,DGV如何填充),在另一個項目中不起作用。 。在DataGridView的特定單元格中設置組合框

//This is my code to go through each cell in the DataGridView. 
for (int i = 0; i < dgvTest.RowCount; i++) 
     { 
      for (int j = 0; j < dgvTest.ColumnCount; j++) 
      { 
       foreach (Information info in frmMain._dbList) 
       { 
        if (dgvTest.Rows[i].Cells[j].Value.ToString().ToLower() == info.InfoName.ToLower() && info.InfoInputType == "1") 
        { 
         DataGridViewComboBoxCell c = new DataGridViewComboBoxCell(); 
         c.Items.Add("0"); 
         c.Items.Add("1"); 
         dgvTest.Rows[i].Cells[(j + 1)] = c; 

        } 
       } 
      } 
     } 

問題:

Error Message

當我點擊 「確定」 奇怪的是,它創建的組合框。如果我重複這個過程,它最終會用ComboBox填充每個單元格,但是隻要我將鼠標懸停在它們上面,就會彈出相同的錯誤消息。

它是否將單元格設置爲組合框,然後嘗試回到同一單元格?

解決

簡單的解決方案 - 必須添加一個c.Value =#設定值。

回答

0

必須將組合框的初始值設置爲某個值。

c.Value = # 
0

爲了避免上述問題。您可以爲您的DataGridView添加DataError事件。

試試下面的代碼:

private void dgvTest_DataError(object sender, DataGridViewDataErrorEventArgs e) 
{ 
    try 
    { 
     if (e.Exception.Message.contains("DataGridViewComboBoxCell value is not valid.")) 
     { 
      object value = dgvTest.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; 
      if (!((DataGridViewComboBoxColumn)dgvTest.Columns[e.ColumnIndex]).Items.Contains(value)) 
      { 
       ((DataGridViewComboBoxColumn)dgvTest.Columns[e.ColumnIndex]).Items.Add(value); 
      } 
     } 

     throw e.Exception; 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(string.Format(@"Failed to bind ComboBox. " 
      + "Please contact support team with below error message:" 
      + "\n\n" + ex.Message)); 
    } 
} 

以上,將引發錯誤信息給用戶。如果你想壓制這個錯誤。您只需按照以下代碼:

private void dgvTest_DataError(object sender, DataGridViewDataErrorEventArgs e) 
{ 
    try 
    { 
     if (e.Exception.Message.contains("DataGridViewComboBoxCell value is not valid.")) 
     { 
      object value = dgvTest.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; 
      if (!((DataGridViewComboBoxColumn)dgvTest.Columns[e.ColumnIndex]).Items.Contains(value)) 
      { 
       ((DataGridViewComboBoxColumn)dgvTest.Columns[e.ColumnIndex]).Items.Add(value); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     //do nothing 
    } 
} 
+0

感謝您的快速回復!在ExceptionPolicy中出現錯誤?這是Visual Studio的內置功能還是HandleException類ExceptionPolicy中包含的方法? – Yahtzee

+0

@Yahtzee不需要它。你只是處理這個異常並顯示消息框。我修改了答案。 –

+0

我不認爲異常正在被打,因爲錯誤信息並不那麼簡單。我編輯了我的問題並上傳了錯誤消息的圖片。 – Yahtzee

相關問題