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.

(171) Comments

Blog Message http://brocktonmassachusedbz.tek-blogs.com/a-vase-filled-with-evergreen-clippings-is-a-handy-buffets-media-cabinets-secretaries-and-so-forth

Premio Yo Emprendo.com Anglica Mara Moncada Muoz


Blog Message http://galen6686hk.recmydream.com/this-look-works-best-if-your-bedroom-has-a-theme-wall-and-you-add-an-element-of-fun-drama-and-romance

Some really choice blog posts on this web site , saved to fav.


Blog Message http://mazraehkatool.ir/user/Beausyacquise185/

Keep up the fantastic piece of work, I read few articles on this site and I think that your site is real interesting and contains bands of superb info.


Blog Message https://www.kouponkabla.com/free-warframe-platinum-codes-2019-latest-here

Many thanks for sharing this fine piece. Very interesting ideas! (as always, btw)


Blog Message http://wrlcaraholic.space/story.php?id=7379

Im thankful for the article post. Fantastic.


Blog Message https://garyappleton.wordpress.com/2019/07/04/uncover-the-ideal-robot-vacuum-for-your-house/

This awesome blog is really awesome and besides amusing. I have discovered helluva handy advices out of this amazing blog. I ad love to visit it every once in a while. Cheers!


Blog Message https://chequesea36.wordpress.com/2019/07/01/sas-a00-280-certification-exam/

It as hard to come by knowledgeable people for this subject, but you seem like you know what you are talking about! Thanks


Blog Message https://www.suba.me/

1Tw3Qz Just Browsing While I was surfing today I noticed a great post concerning


Blog Message https://www.suba.me/

SWzNn7 I think this is a real great blog. Keep writing.


Blog Message http://www.lisakova.com

Really informative blog.Really looking forward to read more.


Blog Message http://www.video-bookmark.com/watch/4057656/best-portable-propane-fire-pits/

This site certainly has all of the information and facts I wanted about this subject and didn at know who to ask.


Blog Message http://gettingshredded.com/the-21-day-plank-challenge-for-a-stronger-and-tighter-core/

Wow, wonderful blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is magnificent, let alone the content!


Blog Message https://goo.gl/dHJ9ZN

pretty handy material, overall I consider this is really worth a bookmark, thanks


Blog Message http://www.rhinojunkremoval.com

Thanks-a-mundo for the blog post.Really thank you!


Blog Message http://www.suvbestinsurance.com

Appreciate you sharing, great article post.Much thanks again. Really Great.

First Previous 1 2 3 4 5 6 7 8 9 10  ... Next Last 
Rating
Name
Email
Comment