Reputation:
I have a DataTable that is acting as the data source for a DataGridView
private readonly DataTable _processTable = new DataTable();
ProcessDataGrid.DataSource = _processTable;
I have a method that populates this DataTable (and in doing so populates the DataGridView)
private void PopulateDataTable()
{
var processes = Process.GetProcesses();
foreach(var process in processes)
{
_processTable.Rows.Add(process.ProcessName);
}
}
I also have a button, that when pressed calls PopulateDataTable
private void RefreshButton_Click(object sender, System.EventArgs e)
{
_processTable.Rows.Clear();
// Refresh the process list
PopulateDataTable();
}
When RefreshButton
is clicked, the data source is cleared and updates correctly, however, it selects a row around half way into the list and scrolls to that value in the DataGridView.
I want to prevent this from occurring, so that when the button is clicked, the data source updates like it is currently doing, however, the no row in automatically scrolled to in the DataGridView (the user's current position relative to the scrollbar doesn't change.)
How could I accomplish this?
Upvotes: 0
Views: 113
Reputation: 1147
Note down the previously selected row index before you refresh the DataTable
. Then select the same row again after refreshing it.
Hint: dataGridViewControl.CurrentRow
is a read-only property, therefore use dataGridViewControl.CurrentCell
for both reading and setting the current row. Make sure you implement a check to see whether CurentCell
property is null
or not and also the row index that you are about to select is NOT beyond the bounds.
Upvotes: 1