2014-10-09 163 views
1

我正在使用DataGridView來顯示來自SQLite數據庫的數據。一列是打開分配給該行的pdf的目錄。代碼工作,但我每次單擊列標題時,它給我的錯誤:單擊標題時DataGridView中出現「索引超出範圍」異常

Index was out of range. Must be non-negative and less than the size of the collection.

其實,任何時候我請單擊列文(只是「PDF」,或任何其他列的文字),它拋出那個錯誤。但是當我點擊文本之外(在排序框中的任何位置)時,它會重新排列我的列,這是正確的。有任何想法嗎?

該代碼起作用,打開PDF,但我不希望用戶不小心點擊標題文本和程序崩潰。這裏是datagridview打開pdf的代碼。

private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e) 
    { 
     string filename = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(); 
     if (e.ColumnIndex == 3 && File.Exists(filename)) 
     { 
      Process.Start(filename); 
     } 
    } 

enter image description here

回答

3

你得到當你點擊標題,因爲RowIndex-1例外。無論如何,您不希望發生任何事情,因此您可以檢查該值並忽略它。

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.RowIndex == -1 || e.ColumnIndex != 3) // ignore header row and any column 
     return;         // that doesn't have a file name 

    var filename = dataGridView1.CurrentCell.Value.ToString(); 

    if (File.Exists(filename)) 
     Process.Start(filename); 
} 

此外,FWIW,你只有當你在標題中單擊文本,因爲你訂閱了CellContentClick(僅火災時,您單擊該單元格的內容,如文本)獲得例外。我建議使用CellClick事件(單擊任何部分單元時觸發)。

+0

謝謝!我知道我必須將rowIndex更改爲-1,但我使用&&而不是||以類似的方式,您在我測試其他方式時編寫代碼。謝謝!像魅力一樣工作! – Onlytito 2014-10-09 14:55:33

+0

哎呀!一個小運營商造成了這麼多問題。 ;) – 2014-10-09 14:57:44