News
  • Favorite
  • Facebook
  • Twitter
  • LinkedIn

Microsoft Press Pearson Education (InformIT)
Skip Navigation Links
Pearson Education (InformIT)
Walkthrough: Maintaining Selected Row of the DataGridView Control after refreshing Data.

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:

1.       Create a new windows application using Visual Studio 2005/2008.

2.       Rename Form1 to OrdersForm.

3.       Add a DataGridView Control to the OrdersForm.

4.       Rename the DataGridView Control to OrdersDataGridView.

5.       Set the data source of the OrdersDataGridView this will create a new binding source. Rename the binding source to ordersBindingSource. You can know more about Windows Forms Data Binding.

6.       Write your code to populate the OrdersDataGridView with data from the database or any other sources.

7.       To refresh data automatically follow these steps:

a.       Add a Timer component to the Form and name it RefreshTimer.

b.      Set the RefreshTimer Enabled property to true.

c.       Set the RefreshTimer Interval to the time (in milliseconds) you want to refresh data each time, for now you can set it to 30000 milliseconds (30 seconds)

d.      Implement the RefreshTimer Tick event and write the code that populates the OrdersDataGridView from the data source.

private void RefreshTimer_Tick(object sender, EventArgs e)

      {

         //Write the Code that populates the DataGridView with data from datasource.

}

8.       For now you can run the application and check you will see that each 30 seconds data will be refreshed.

9.       If you selected an order in the OrdersDataGridView and new orders have been added in the data source, the selected order is lost and another order is now selected.

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.

10.   Now we will maintain the selected order in the OrdersDataGridView using the following steps:

a.       Add a string global variable named selectedOrder to the OrdersForm. This variable will be used to save the selected order Id to be used later.

b.      Implement the SelectionChanged event of the OrdersDataGridView Control.

c.       In the SelectionChanged event we will set the selectedorder to the selected order Id as follows

if (OrdersDataGridView.SelectedRows.Count > 0)

{

selectedOrder = OrdersDataGridView.SelectedRows[0].Cells[“Order Id Column Index”].Value.ToString();

}

d.      The above code simply checks if any of the OrdersDataGridView row is selected and assigns the selected orderId to the selectedOrder variable.

e.      In the above code replace Order Id Column Index with the index of the orderId Column.

f.        Now we save the selected order Id.

g.       Implement the DataBindingComplete of the OrdersDataGridView Control and write the following code

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;

      }

   }

h.      The above code simply checks if the selected Order variable has a value.

i.         If the selected Order has a value, then we use the Find method of the Binding Source component to find the new index of the selected order.

j.        If we found the selected order in the binding source we get its new index in the binding source items.

k.       If we found the new index, then we mark this row as selected in the OrdersDataGridView.

l.         If the order is not found the binding Source, then we set the selected row to the row with index 0.

 

Now you have a DataGridView that maintains the selected row according to the data itself not the index of the selected row.

(47) Comments

Blog Message louis vuitton sale

Manufacturer Burton Wimbley from Weymouth, likes to spend time creating, nike free and canoeing. Has completed a wonderful around the world journey that included going to the Changdeokgung Palace Complex. louis vuitton sale http://www.whalebonehouse.com#


Blog Message kate spade handbags outlet

Traditional Asian Medical Practitioner Rafael Chalifour from McKellar, loves to spend some time studying a foreign language, nike free and digital photography. Did a cruise liner experience that consisted of passing by Historic Centre of Rome. kate spade handbags outlet http://www.miracles-in-europe.com#


Blog Message chi flat iron

49 yr old Gardener (Normal ) Bonacci from Regina, spends time with passions for example 4 wheeling, nike free and tetris. Last month just arrived at Ancient Building Complex in the Wudang Mountains. chi flat iron http://www.cushingfirstfreewill.org#


Blog Message michael kors outlet online

Student Counsellor Rusty from Dawson Creek, has many pursuits that include lacross, nike free and russian dolls collecting. Felt especially enthused after building a journey to Piazza del Duomo. michael kors outlet online http://www.aqualinkservis.com#


Blog Message toms outlet

22 yrs old Translator Burton Budzinski from La Loche, has pastimes such as hot air ballooning, nike free and string figures. Keeps a travel site and has lots to write about after going to Derwent Valley Mills. toms outlet http://www.beargryllsfansite.com#


Blog Message michael kors outlet online sale

47 yr old Equipment Hire Manager Anderson from Kingston, spends time with hobbies for example caravaning, nike free and casino gambling. Has become inspired how vast the earth is after setting up a journey to Old Town of Ghadamès. michael kors outlet online sale http://www.7specialgift.com#


Blog Message louboutin shoes

52 yr old Contract, Challenge or Program Administrator Anderson Chalifour from Sardis, loves to spend time going to movies, nike free and tea tasting. Recalls what a beautiful spot it was having made a vacation in Sanctuary of Asklepios at Epidaurus. louboutin shoes http://www.al-khlaf.com#


Blog Message louis vuitton bags

Community Worker Mulroy from Saint-Jerome, spends time with hobbies for instance snowshoeing, nike free and television watching. Keeps a tour blog and has heaps to write about after visiting Gusuku Sites and Related Properties of the Kingdom of Ryukyu. louis vuitton bags http://www.asesoriaspsicologicasappi.com#


Blog Message gucci 財布 小さく

the accommodation has an atm machine, become dry washing software, product look, assistant table, hotel web site rrncluding a shuttle to make sure you closest sight-seeing opportunities consisting of dependent ground. the main hotel's health club makes free weights and in addition cardio exercise resources. the accommodation boasts a running tune and as well an outdoor billiard. gucci 財布 小さく http://www.countryplazataree.com.au/product/shop.asp?id=393


Blog Message louboutin shoes

57 year old Archivist Rafael from Chesley, spends time with hobbies and interests which includes frolf (frisbee golf), nike free and hot rods. During the recent few months has visited to locations for example Birka and Hovgården. louboutin shoes http://www.al-khlaf.com#


Blog Message kate spade handbag

Chemical Seed Operator Oley from Laterriere, has lots of hobbies and interests which include reading to the, nike free and television watching. Constantly enjoys going to destinations including Surtsey. kate spade handbag http://www.skehanaghlodge.com#


Blog Message new balance 996

35 year old Composer Anderson Faulhaber from La Romaine, has hobbies for instance curling, nike free and films. Gets motivation through travel and just spent 3 months at . new balance 996 http://www.kaptiv-8.com#


Blog Message kate spade outlet online

Careers Counsellor Purchase from Newton, spends time with hobbies such as koi, nike free and digital photography. Gains enormous encouragement from life by touring destinations like Swiss Alps Jungfrau-Aletsch. kate spade outlet online http://www.wickedzoot.com#


Blog Message michael kors outlet online sale

43 yr old Contract, Challenge or Program Administrator Dority from Weyburn, usually spends time with hobbies like juggling, nike free and tombstone rubbing. Intends to retire and take the family to many of the noteworthy heritage listed places in the world like The Subak System. michael kors outlet online sale http://www.nesbcnh.com#


Blog Message toms outlet store

39 yr old Physiotherapist Dority from Masson, has numerous pursuits which include cycling, nike free and bee keeping. During the last year has completed a visit to Kinabalu Park. toms outlet store http://www.freeflagstaffmls.com#

First Previous 1 2 3 4 Next Last 
Rating
Name
Email
Comment