我在DataGridView中打开一个CSV文件。当我单击"Down“按钮时,下一行将被选中。问题:当我打开一个新的CSV并单击"Down“时,选择会自动跳转到旧CSV最后选定的编号的行号。
示例:我选择了第11行并打开了一个新文件。第1行被选中,直到我按下"Down“。而不是第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;
}
}
发布于 2017-09-13 18:06:50
您不应该使用内部计数器来存储选定的行,因为其他组件可以更改所选内容(在您的情况下,通过更改数据源)。只需使用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;
}
}
}
https://stackoverflow.com/questions/46203969
复制相似问题