Sometimes you need to maintain the selected row that you want to take an action on. If you make a refresh of data in the DataGridView the selected row will be lost, especially when you refresh data in a separate thread. In this article we will know how to maintain the selected row in the DataGridView Control using C#.
First of all let me show you the scenario that this article may benefit. Suppose that you have created an application that customers uses to place orders. These orders are reviewed by an employee in the company and after review it passes the selected order to be executed. These orders are refreshed automatically. Suppose the employee has selected an order and then passes that order while he passes the order the data is refreshed and the employee has found that he passes another order not the previously selected one.
So you have to maintain the selected order while refreshing data to overcome this problem.
Suppose you have a database table named orders, the orders table has a primary key column named order Id. In the following steps you will create an application to get orders from the database and display them in a DataGridView Control using the BindingSource component.
To maintain the selected row in the DataGridView Control follow these steps:
private void RefreshTimer_Tick(object sender, EventArgs e)
{
//Write the Code that populates the DataGridView with data from datasource.
}
Note: The DataGridView maintains the selected index only that means that if you select row number 7 and refresh data the row number 7 will be selected.
if (OrdersDataGridView.SelectedRows.Count > 0)
{
selectedOrder = OrdersDataGridView.SelectedRows[0].Cells[“Order Id Column Index”].Value.ToString();
}
if (!string.IsNullOrEmpty(selectedOrder) && e.ListChangedType == ListChangedType.Reset)
{
if (ordersBindingSource.List.Count > 0)
{
selectedIndex = ordersBindingSource.Find(“Orderid Column Name”, selectedOrder);
if (selectedIndex <= 0)
selectedIndex = 0;
OrdersDataGridView.Rows[selectedIndex].Selected = true;
}
else
{
selectedOrder = string.Empty;
}
}
Now you have a DataGridView that maintains the selected row according to the data itself not the index of the selected row.
15 March 2022
17 February 2022
09 December 2019