【问题标题】:C# DataGridView reset row new fileC# DataGridView 重置行新文件
【发布时间】:2026-01-18 09:50:01
【问题描述】:

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

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

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;
    }
}

【问题讨论】:

  • 嗨。您可能需要发布更多上下文。您的 sn-p 指的是在 sn-p 之外定义的许多变量,因此很难说发生了什么。

标签: c# csv datagridview row selected


【解决方案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;
        }
    }
}

【讨论】:

  • 工作正常。非常感谢!