Results 1 to 3 of 3

Thread: Datagrid to keep selected row and position after refresh

  1. #1

    Thread Starter
    Member
    Join Date
    May 2008
    Posts
    52

    Datagrid to keep selected row and position after refresh

    Hi guys, I have a datagrid which starts off blank and slowly gets populated as processes execute. It also refreshes every 5 seconds using the timer.

    The problem I have is, after it refreshes it resets the view to the top of the list. So you may have scrolled down and selected the 20th item in the list, but after the refresh it's back to the top.

    I tried the below code but I get an error because the grid is empty to start with and it can't get the index location.

    Code:
    i = HistoryDataGridView.CurrentRow.Index
     HistoryDataGridView.CurrentCell = HistoryDataGridView.Rows(i).Cells(1)
    Error I get is:
    Additional information: Object reference not set to an instance of an object

    Whats the best way to handle this?

    One other question, how do I get the datagrid to retain it's current position? If for example I have scrolled down 40 rows, how do I get it stay there after the refresh?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Datagrid to keep selected row and position after refresh

    What exactly is this "refresh" of which you speak? Do you mean that you remove all the rows and then repopulate the it? If so then there is no "staying" because if there are no rows in between then there can be no current row or scrolling position. You would need to remember the current row and scrolling position before removing all the rows, then reinstate them after the rows are re-added.

    The code you have shown is correct in principle but the first line needs to be executed BEFORE removing all the rows and the second line AFTER re-adding them. You would need to do the same for the scrolling position, for which you would use the FirstDisplayedScrollingRowIndex property.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Member
    Join Date
    May 2008
    Posts
    52

    Re: Datagrid to keep selected row and position after refresh

    By refresh I mean rebinding the datasource.

    As for my problem, I managed to sort it out using a try catch (maybe not the best or most elegant, but does the job)

    And for the scroll position I used the FirstDisplayedScrollingRowIndex as you suggested, Thanks.
    Last edited by amaru96; Dec 14th, 2014 at 04:26 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width