Always Show Selected Row of a DataGridView in C# / CSharp

The following codes will always Show the Selected Row of a DatagridView when the data is reloaded and will recall the state of the scrollbar by its scroll value..

CODE:
private int scrollVal = 0, rowIndex = 0, lastRow = 0;

private void datagridView1_Scroll(object sender, EventArgs e) 
    {
        //WILL USE THE SCROLL VALUE LATER WHEN RELOADING THE DATAGRIDVIEW
        scrollVal = datagridView1.VerticalScrollingOffset;
    }

private void datagridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        //GETS THE INDEX OF THE CURRENT SELECTED ROW
        rowIndex = this.datagridView1.CurrentRow.Index;
        rowIndex = rowIndex != 0 ? lastRow = rowIndex : lastRow = rowIndex;
    }

private void reloadDatagridView()
    {
        //RELOADS DATA OF THE DATAGRIDVIEW
        datagridView1.Clear();
        datagridView1.DataSource = "Your Data Table";
        datagridView1.AutoGenerateColumns = true;
        datagridView1.MultiSelect = false;
        datagridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
        datagridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells); 
        
        datagridView1.Rows[lastRow].Selected = true;
        
        int rowHeight = datagridView1.Rows.GetRowsHeight(DataGridViewElementStates.Selected);
         
        datagridView1.FirstDisplayedScrollingRowIndex = scrollVal / rowHeight;
 
        datagridView1.Refresh();
    }
HOW IT WORKS:
scrollVal:
Every time the user scroll's the control it will get the scrolling offset of the scroll bars.

lastRow:
When the user clicks anywhere on the DatagridView's Cell it will get the Selected Row's Index and assign to lastRow variable. The lastRow variable will then be used as the Index of the Row that will be selected when the DatagridView is reloaded.

rowHeight:
Get's the height of the DatagridViewRow's Selected element state.

.FirstDisplayedScrollingRowIndex = scrollVal / rowHeight:
Set's the Scroll Value of the DatagridView when the data is reloaded.

Comments

Popular posts from this blog

How to Create a Configuration.INI Files in VB6

How to Set Windows Form Always on Top of Other Applications in VB6

How to Minimize/Send an App Icon to System Tray in Visual Basic 6