2017-03-27 167 views
0

我正在嘗試更新DataGridView。更新它隨機拋出異常(不是每次都是)。更新DataGridView時發生意外的異常:「索引超出了數組的範圍」即使索引正確

foreach (DataGridViewRow row in dataGrdVwReport.Rows) 
{ 
     try 
     { 
      f_RowIndex = row.Index; 
      f_ColCount = row.Cells.Count; 
      row.Cells[2].Value = p_Count; //Exception here 
     } 
     catch (Exception ex) 
     { 
      m_objLogFile.Error(CLASS_NAME + "->" + METHOD_NAME + "() : inner foreach : " + "f_RowIndex = " + f_RowIndex); 
      m_objLogFile.Error(CLASS_NAME + "->" + METHOD_NAME + "() : inner foreach : " + "f_ColCount = " + f_ColCount); 
      m_objLogFile.Error(CLASS_NAME + "->" + METHOD_NAME + "() : inner foreach : " + "p_Count= " + p_Count); 
      m_objLogFile.Error(CLASS_NAME + "->" + METHOD_NAME + "() : inner foreach : " + ex.Message); 
     } 

例外是:

指數陣列的邊界之外。

堆棧跟蹤是:

在System.Windows.Forms.PropertyStore.GetObject(的Int32鍵,布爾&實測值) 在System.Windows.Forms.DataGridViewCellStyle.set_SelectionBackColor(顏色值) 在System.Windows.Forms.DataGridViewCell.GetInheritedStyle(的DataGridViewCellStyle inheritedCellStyle,的Int32 rowIndex位置,布爾includeColors) 在System.Windows.Forms.DataGridViewCell.GetPreferredHeight(的Int32 rowIndex位置,的Int32寬度) 在System.Windows.Forms.DataGridViewRow.GetPreferredHeight(的Int32 rowIndex,Da taGridViewAutoSizeRowMode autoSizeRowMode,布爾固定寬度) 在System.Windows.Forms.DataGridView.AutoResizeRowInternal(的Int32 rowIndex位置,DataGridViewAutoSizeRowMode autoSizeRowMode,布爾固定寬度,布爾internalAutosizing) 在System.Windows.Forms.DataGridView.OnCellCommonChange(的Int32 columnIndex,的Int32 rowIndex位置) 在System.Windows.Forms.DataGridView.OnCellValueChanged(DataGridViewCellEventArgs E) 在System.Windows.Forms.DataGridView.OnCellValueChangedInternal(DataGridViewCellEventArgs E) 在System.Windows.Forms.DataGridViewCell.SetValue(的Int32 rowIndex位置,對象的值) 在系統。 Windows.Forms.DataGridViewCell.set_Value(Object value)

發生Fisrt時間異常,Count爲: RowIndex = 0:RowCount = 1; ColumnCount = 9; P_Count 15

我試了一遍: RowIndex = 0:RowCount = 1; ColumnCount = 9; P_Count 93

同樣是: RowIndex = 0:RowCount = 1; ColumnCount = 9; P_Count 7

如果我刪除完整的行&與更新後的值重新插入。在這種情況下,沒有什麼異常。但是我想編輯特定的細胞.. &我認爲刪除&重新插入行不是有道..這是耗時..

請建議解決方案。

+1

多少列貴的datagridview有哪些? –

+0

看來你的datargid只有不到3列。考慮到索引是零基於 – apomene

+0

9列..及其拋出異常隨機..並非每次.. – Renuka

回答

0

你有沒有嘗試過這樣的事情來找出你的錯誤來自哪裏? 你之後已經發現並修復可以去除嘗試捕捉錯誤

foreach (DataGridViewRow row in dataGrdVwReport.Rows) 
{ 
    try 
    { 
     row.Cells[2].Value = p_Count; //Exception here 
    } 
    catch (exception ex) 
    { 
     // write code here to log the rowcount, columncount, p_count, and other stuff here 
     throw; 
    } 
} 
+0

是的,我已經添加在try catch塊已代碼..所以,我已經證明異常及堆棧跟蹤..&異常是不特定的行..這是非常隨機.. – Renuka

+0

,什麼是列數?和rowcount? – GuidoG

+0

發生Fisrt時間異常,Count爲: RowIndex = 0:RowCount = 1; ColumnCount = 9; P_Count 15 我試了一遍: RowIndex = 0:RowCount = 1; ColumnCount = 9; P_Count 93 同樣是: RowIndex = 0:RowCount = 1; ColumnCount = 9; P_Count 7 – Renuka