2012-06-22 34 views
3

我有一個C#winforms應用程序,我試圖得到一個按鈕的工作,將選擇一個datagridview中的下一行後,一個curently選擇。DataGridView導航到下一行

我到目前爲止的代碼是:

private void button4_Click(object sender, EventArgs e) 
{ 
    try 
    { 
    Int32 selectedRowCount = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected); 

    // index out of range on this line 
    dataGridView1.Rows[dataGridView1.SelectedRows[selectedRowCount].Index].Selected = true; 

    dataGridView1.FirstDisplayedScrollingRowIndex = selectedRowCount + 1; 
    } 
    catch (Exception ex) 
    { 
    return; 
    } 

但在運行此它拋出一個異常。任何人都可以指出我可能會出錯的地方。拋出的錯誤是:Index is out of range

回答

7

嘗試:

int nRow; 
private void Form1_Load(object sender, EventArgs e) 
{ 

    nRow = dataGridView1.CurrentCell.RowIndex; 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    if (nRow < dataGridView1.RowCount) 
    { 
     dataGridView1.Rows[nRow].Selected = false; 
     dataGridView1.Rows[++nRow].Selected = true; 
    } 
} 
+0

謝謝。這在一定程度上起作用。它希望它取消選擇前一行。 – L337BEAN

+0

我編輯的代碼再次看到它 – KF2

+0

這是完美的謝謝你。我現在看到我應該做的事情。 – L337BEAN

1

它在這裏:

dataGridView1.SelectedRows[selectedRowCount] 

如果你有3個選擇的行然後selectedRowCount = 3和有三排索引:0,1,2

你是試圖訪問不存在的#3。

+0

啊我明白了。你能建議一種方法來達到我尋找的結果嗎? – L337BEAN

0

這個例子中讀取值細胞或列是datagridview的4號

 int courow = dataGridView1.RowCount-1; 
     for (int i=0; i < courow; i++) 
     { 
      MessageBox.Show(dataGridView1.Rows[i].Cells[4].Value.ToString()); 
     } 
-1
dgv_PhotoList.Rows[dgv_PhotoList.CurrentRow.Index+1].Selected = true; 
1

首先,設置 「複選」 daatgridview的屬性來假。

int currentRow = dataGridView1.SelectedRows[0].Index; 
if (currentRow < dataGridView1.RowCount) 
{ 
    dataGridView1.Rows[++currentRow].Selected = true; 
} 

它會選擇datagridview中的下一行。

0

選擇行和單元以獲得更好的解決方案。 此解決方案在DataGridView上移動行指示符。

private void _GotoNext(object sender, EventArgs e) 
    { 
     int currentRow = DataGridView1.SelectedRows[0].Index; 
     if (currentRow < DataGridView1.RowCount - 1) 
     { 
      DataGridView1.Rows[++currentRow].Cells[0].Selected = true; 
     } 
    } 

    private void _GotoPrev(object sender, EventArgs e) 
    { 
     int currentRow = DataGridView1.SelectedRows[0].Index; 
     if (currentRow > 0) 
     { 
      DataGridView1.Rows[--currentRow].Cells[0].Selected = true; 
     } 
    }