2017-09-13 62 views
0

我在我的DataGridView中打开一个CSV文件。当我点击按钮“下”时选择下一行。 问题:当我打开一个新的CSV并点击“向下”时,选择会自动跳转到最后选择的旧CSV编号的行号。C#DataGridView重置行新文件

示例:我选择第11行并打开一个新文件。第1行被选中,直到我按下“向下”。取代第2行,选择第11行。

private void btn_down_Click(object sender, EventArgs e) 
{ 
    if (dataGridView1.Rows.Count != 0) 
    { 
     selectedRow++; 
     if (selectedRow > dataGridView1.RowCount - 1) 
     { 
      selectedRow = 0; 
      port.Write("..."); 
     } 
     dataGridView1.Rows[selectedRow].Selected = true; 
     dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.SelectedRows[0].Index; 
    } 
} 
+0

嗨。您可能需要发布更多的上下文。您的代码段指的是在片段外定义的一些变量,因此很难说出发生了什么。 – mhvelplund

回答

1

你不应该使用一个内部计数器来存储选定行,因为可以选择其他组件(通过改变数据源在您的情况)来改变。只需使用dataGridView1.SelectedRows即可获取当前选定的行。根据这一行选择下一个。这里是一个简单的实现:

private void btn_down_Click(object sender, EventArgs e) 
{  
    //Make sure only one row is selected 
    if (dataGridView1.SelectedRows.Count == 1) 
    { 
     //Get the index of the currently selected row 
     int selectedIndex = dataGridView1.Rows.IndexOf(dataGridView1.SelectedRows[0]); 

     //Increase the index and select the next row if available 
     selectedIndex++; 
     if (selectedIndex < dataGridView1.Rows.Count) 
     { 
      dataGridView1.SelectedRows[0].Selected = false; 
      dataGridView1.Rows[selectedIndex].Selected = true; 
     } 
    } 
} 
+0

工作正常。非常感谢! – Tomy