[英]Index out of range exception in datagridview when header is selected
[英]Getting “Index was out of range” exception in DataGridView when clicking header
我正在使用DataGridView來顯示來自SQLite數據庫的數據。 一欄是打開分配給該行的pdf的目錄。 該代碼有效,但是,每當我單擊列標題時,都會出現錯誤:
索引超出范圍。 必須為非負數並且小於集合的大小。
實際上,每當我單擊列文本(僅“ 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);
}
}
單擊標題時會出現異常,因為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
事件(在單擊單元格的任何部分時觸發)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.