VB.NET: DatagridView / DataAdapter / InsertCommand - cannot update database after adding new row to datagridview

Posted on 2007-08-01
Last Modified: 2013-12-20
I am using VB.NET 2005.
I set up a dataadapter with an  InsertCommand, UpdateCommand and DeleteCommand.
I have a datagridview on the form.
The datagridview has 6 columns.  
An ID column (which is hidden), an Identifier column, a Description column and a few other columns.
The Identifier column and Description column are the only 2 columns that are editable/writeable.
What I want to do is update the database using the dataadapters InsertCommand after a user adds a new row to the grid.......which is to say the user naviated to the NewRow row in the grid, manually entered information into the 2 columns (Identifier, Description) and then hit the Return Key (or used an arrow key to naviate to another row in the grid).

I cannot seem to accomplish this goal.  It seems that if I execute the InsertCommand on that datagrids LeaveRow method, it is not getting all the data for the row I just left.
(ie. Say I enter an Identifier in the 1st column.  Then I tab to the 2nd columns.  Enter a description, then hit enter.  When it falls into the LeaveRow event, it doesnt see any data in the 2nd column - and Im guessing whatever object contains the 'added rows' for the datagridview, does not have the infomation that I just entered.)

Can anyone help me out here?  I'm guessing it shouldn't be toooooo difficult to commit an addition to a database after the user leaves focus of the AddNew row - but I seem to be having a little bit of trouble with it.

Thank you in advance for your help.

Question by:fesit
    LVL 18

    Expert Comment


    Try have a look at this link

    there are 2 missing point you do not mention.

    1) is your table setup with a primary key?

    2) have a look at the commandbuilder object.

    LVL 48

    Expert Comment

    Some questions ?

    1 - Have you any filter on binding source ?
    2 - Does your ID from the database is set to Primary Key ?
    LVL 48

    Expert Comment

    Same time VBturbo ... lol

    Author Comment

    I do have a key on the table I need to update.

    If I had an "Update" button on the form that I made the user click to update all Inserted, Deleted and Updated rows, it works fine.  That is the way I had it working originally.

    I was trying to make it more user friendly: "less clicks."
    I wanted the changes to go into effect immediately.

    For example, when a Description is getting updated, I update the DB using the CellEndEdit method.
    I update Deletes using the RowsRemoved method.
    But I cannot figure out a way to insert the Added records.
     I cannot use the CellEndEdit, because I have to update two cells.
    The RowLeave does not work because that fires BEFORE the CellEndEdit, therefore it doesn't see any data in the 2nd cell when it is in RowLeave.

    I already have defined my InsertCommand, UpdateCommand and DeleteCommand.
    As I said, if I force the user to click a button to call these updates, everything is fine.  I was looking for a more efficient, user friendly (less clicks) way of doing it.

    Any ideas?

    LVL 48

    Expert Comment

    And in the UserAddedRow Event, have you tried ?

    Author Comment


    I thought I may have overlooked the easiest and most obvious way of handling this ...

    But I just tried the UserAddedRow - I think I tried it yesterday at some point and just forgot -
    This event got fired as soon as i typed the first letter in the first column of the new row.
    I need something to fire after I am done adding the row.
    LVL 48

    Expert Comment

    Can you, for the new rows, check if you have filled the rows you need ?

    Then you can update on the CellEndEdit if the row 1 and 2 are filled.

    Author Comment


    I tried that too....
    This is the problem.....
    I have a column with the ID (which is the key in the DB) -
    On the CellEndEdit, I was checking to see if both columns I was adding were filled with data, and checking to see if the ID column was IsDBNull.
    This works - and it calls the update:
    daEntitlements.Update(dt.Select(Nothing, Nothing, DataViewRowState.Added))
    However, nothing gets added to the db.  I guess its not part of the DataViewRowState.Added collection.

    How do I access the .Added collection to see what's in it?
    But anyway, it does not work on the CellEndEdit.
    It will hit the update, but the DB is not updated.
    If i re-set focus to that newly added row a 2nd time, edit a cell, and lose focus on the row again, it fires the .Update again, and this time it works....
    But on the initial lose focus of the row, the .Update does not work.

    Im really at a loss right now.

    I added text to the 1st cell.  Added text to the 2nd cell.  When that cell lost focus, it would update the DB because both cells had values nd

    Author Comment

    sorry - disregard the
    "I added text to the 1st cell.  Added text to the 2nd cell.  When that cell lost focus, it would update the DB because both cells had values nd"

    it was something i copied to reference, but meant to delete.
    that last comment should have ended at "Im really at a loss right now."  which i still am.
    LVL 18

    Expert Comment

    have you tried the the grids mode into:


    before doing a update ?

    the CellEndEdit() is more a method to use  when  you entered some data you want to be validated before tabbing along.

    a different approach is to send an enter key to the grid! meaning give the grid focus and then
    to end any state of the grid's "edit mode"  then you are defently able to update whitout loosing data.


    Author Comment

    I really cannot figure this out.
    I tried putting the .EndEdit code in the _RowLeave event and the _CellEndEdit.
    Didnt work for either one.
    Also tried the SendKeys.Send in both.  That didnt work either.

    So then I tried putting both pieces of code in both events.
    Still doesnt work.

    (I really appreciate your help - both of you: Vturbo and jPaulino - I really hope we can figure this out somehow)

    LVL 48

    Accepted Solution

    Sorry fesit I cannot understand your point. If you want to validate you can try RowValidation. RowValidation fire when you enter or leave the row and with some condition you can achieve it.

    This is an example that Im using without any problem. I think thats the easy way (at least for me!)

    Im populating the datagridview from the access selecting the datasource from a dataset (automatically creates the bindingsource, dataadapter)

    On form load event:
    Me.RepBindingSource.Filter = "repdata is null"

    On btnSave click (btnSave but could be RowValidation event )
    Me. RepTableAdapter.Update(Me. myDataSet. DataSetName)

    Author Comment

    I think this pretty much worked
        Private Sub grdManage_RowValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdManage.RowValidated
            If m_FormState <> "Load" Then
                If IsDBNull(CType(sender, DataGridView).Rows(e.RowIndex).Cells("coManageEntitlementID").Value) Then
                    If CType(sender, DataGridView).Rows(e.RowIndex).Cells("coManageEntitlement").Value.ToString <> Nothing Then
                    End If
                End If
            End If
        End Sub

    _RowValidated seemed to work.
    But now I'm having other issues.
    If I delete a row in the grid (and update that delete in the db realtime) it gives me and error when i try to add a row - something about the internal index getting messed up.
    I have a REFRESH button on the form that re-queries the db and reloads the grid...
    If i click the button, after any update, its fine.  If I call the REFRESH code from the _RowValidated event, the code crashes.  
    I have no idea whats going on - so I think I'm just going to put all the Updating code for the Updates, Deletes and Adds on the _FormClosed method.
    This is just turning into too much of a headache.
    All of this because I was trying to save the user 1 or 2 clicks...wanted to make it REALLY user friendly.
    Oh well.
    Thank you JPaulino and VBTurbo for your help.
    It is greatly appreciated.

    Featured Post

    Gigs: Get Your Project Delivered by an Expert

    Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

    Join & Write a Comment

    When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most p…
    Article by: Martin
    Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
    Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
    Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now