Share via

Datagridview C# how to stop autoscrolling to first row after every cell update

Martin Nikodijevic 20 Reputation points
2023-12-22T11:22:35.9+00:00

Can anyone show me how to stop my Datagridview from scrolling to first row after every cell update?

I'm using timer to auto refresh cell data.

Recept 2023-12-22 12-17-39.gif

Developer technologies | .NET | Other
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author
  1. Jiachen Li-MSFT 34,241 Reputation points Microsoft External Staff
    2023-12-22T11:58:37.4366667+00:00

    Hi @Martin Nikodijevic ,

    Create a global variable that records the currently selected row and column indexes, and restores the previous selected state of the cell when the DataGridView is refreshed during the timer tick event.

    For example:

    int selectedRowIndex = -1;
    int selectedColumnIndex = -1;
    
    private void RecordSelectedCell()
    {
        if (dataGridView1.SelectedCells.Count > 0)
        {
            selectedRowIndex = dataGridView1.SelectedCells[0].RowIndex;
            selectedColumnIndex = dataGridView1.SelectedCells[0].ColumnIndex;
        }
        else
        {
            selectedRowIndex = -1;
            selectedColumnIndex = -1;
        }
    }
    
    
    private void timer1_Tick(object sender, EventArgs e)
    {
    
        RecordSelectedCell();
    
        if (selectedRowIndex >= 0 && selectedColumnIndex >= 0 &&
            selectedRowIndex < dataGridView1.Rows.Count &&
            selectedColumnIndex < dataGridView1.Columns.Count)
        {
            dataGridView1.ClearSelection();
            dataGridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Selected = true;
        }
    }
    
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.