2013-05-01 75 views
0

當我使用帶有重載的ToString()方法的類對象加載組合框的列時,我收到dataGridView的異常。如何處理來自DataGridView的錯誤

我已經嘗試了一切,我可以在互聯網上找到,以防止這個錯誤,我還有另一個開放的問題,所以試圖排除這一個,但我沒有成功。

我收到的最直接的答案是處理錯誤信息,並阻止它加載,在這種程度上我搜索了一遍,並創建了這種方法,我相信應該可以解決這個問題。

private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError) 
{ 
    anError.Cancel = true; 
} 

它有點粗糙,但我相信它應該工作,但是當我添加斷點,錯誤仍然存​​在,從不闖入這個功能。我之前從未做過任何錯誤處理,而且很可能我錯過了一些東西。

所有協助讚賞。

+0

http://www.codeproject.com/Articles/18814/A-method-that-provides-how-to-handle-events-when-m將幫助你 – 2013-05-01 07:05:06

+0

你不需要做任何事情,即使處理空,它會忽略錯誤。在沒有錯誤的地方我已經有了這個。 – Derek 2013-05-01 08:15:34

+0

剛剛嘗試了什麼德里克建議。它沒有奏效。我有類Form1中的那個事件處理函數,它是否在別的地方? – 2013-05-01 11:32:33

回答

0

是的,它畢竟是簡單的。

private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError) 

需要重新命名。

private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError) 

首都D女士們,先生們。

感謝您的幫助。

0

德一看這...

private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError) 
{ 

MessageBox.Show("Error happened " + anError.Context.ToString()); 

if (anError.Context == DataGridViewDataErrorContexts.Commit) 
{ 
    MessageBox.Show("Commit error"); 
} 
if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange) 
{ 
    MessageBox.Show("Cell change"); 
} 
if (anError.Context == DataGridViewDataErrorContexts.Parsing) 
{ 
    MessageBox.Show("parsing error"); 
} 
if (anError.Context == DataGridViewDataErrorContexts.LeaveControl) 
{ 
    MessageBox.Show("leave control error"); 
} 

if ((anError.Exception) is ConstraintException) 
{ 
    DataGridView view = (DataGridView)sender; 
    view.Rows[anError.RowIndex].ErrorText = "an error"; 
    view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error"; 

    anError.ThrowException = false; 
} 
} 

閱讀此鏈接:DataGridViewDataErrorEventArgs

0

您必須在文件 「YourForm.Designer.cs」 在項目中插入一行代碼

this.dataGridView1.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView1_DataError); 

將此方法添加到文件「YourForm.cs」

private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError) 
    { 
     MessageBox.Show("Error happened " + anError.Context.ToString()); 
    }