简体   繁体   中英

C# DataGridView reset row new file

I open a CSV File in my DataGridView. When i click on button "Down" the next row is selected. Problem: when I open a new CSV and click "Down", automatically the selection jumps to the row number of the last selected number of the old CSV.

Example: I select row 11 and open a new file. Row 1 is selected until I press "Down". Instead of row 2, row 11 is selected.

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

You should not use an internal counter to store the selected row since the selection could be changed by other components (in your case by changing the data source). Just make use of the dataGridView1.SelectedRows to get the currently selected row. Based on this row select the next one. Here is a simple implementation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM