none
Bound data from LinqToSql in DataGridView: refresh & undo RRS feed

  • Question

  • Hello,

    I'm trying to design a simple form in vb.net where users can enter codes and a description in a bound datagridview. LinqToSql seems an easy way for doing that.

    So I've added a datacontext to my project, dragged the sql-table TEST_TABLE on it and used following code to fill the gridview:

        Dim db As New DataClasses1DataContext
        Dim bs As New BindingSource()

        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Fill_Grid()
        End Sub

        Private Sub Fill_Grid()

            bs.DataSource = (From ld In db.TEST_TABLEs
                                      Select ld)

            DataGridView1.DataSource = bs

        End Sub

    This works great, and by adding a save-button to my toolbar with the db.submitchanges command I can add and update the data.

    But now I wanna add a refresh button, one that refreshes the datagridview from the sql-database (eg. to show changes in the table made by other users):

        Private Sub cmdRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Fill_Grid()
        End Sub

    This doesn't seem to work, since the data in my datacontext won't be updated this way. So I can re-create the datacontext in my fill_grid:

        Private Sub Fill_Grid()

            db = Nothing
            db = New DataClasses1DataContext

            bs.DataSource = (From ld In db.TEST_TABLEs
                             Select ld)

            DataGridView1.DataSource = bs

        End Sub

    This works, but does this mean every table in my datacontext will be reloaded? I mean I'll have about 100 sql-tables with millions of records in my project. Does the datacontext only load data when I use a Linq query, or is everything cached with the "new" command?

    Also, is this the right way to refresh the data from database in my gridview?

    Another problem: I wanna add an undo-button, to get rid of the changes since the last db.submitchanges:

        Private Sub cmdCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            bs.CancelEdit()
        End Sub

    This doens't seem to work. The gridview is getting out of editmode, but the original value is not restored in the gridview. What's the correct way of doing this?

     

    Thankx a lot for any help!

    Erik

     

     

    Wednesday, January 26, 2011 11:51 AM

Answers

  • >This doesn't seem to work, since the data in my datacontext won't be updated this way. So I can re-create the datacontext in my fill_grid:

    That is incorrect, a datacontext is not a cache. When directed it faithfully gets the data. Rebinding to the grid should show the current state of the database, unless I am missing something.


    William Wegerson (www.OmegaCoder.Com)
    Thursday, January 27, 2011 11:06 PM
    Moderator