Bound Datagridview: adding multiple rows and save after each add

I am using a Datagridview that is Bound to a Bindingsource.  I add one row by typing values in it and when I leave the row my code writes the additions back to the database. Now here's the problem: Once I enter the 2nd new row no value is automatically entered in the Identity column (like in the first new row) and as soon as I start typing in one of the cells (not the Identity one)  VB Express 2005 starts throwing exceptions (Index N doesn't have a value).

I want to save each new record after it is added so that I can make sure no duplicates are being added.

Any idea how to fix this
      
Thanks
Simmy

OK, I have figured how to add each record by itself and still have it increment the Identity column. Now the problem is that after adding the first new row there is always an extra row at the end of the DataGridView.

Any Ideas
Simmy

This is the code I am using to save the added record:

      Dim AddedRecords As System.Data.DataTable = _
                             NDataSet.Tables("Departments").GetChanges(DataRowState.Added)
      If Not (AddedRecords Is Nothing) Then
        DTableAdapter.Update(AddedRecords)
        NDataSet.Tables("Departments").AcceptChanges()       
      End If


 



Answer this question

Bound Datagridview: adding multiple rows and save after each add

  • PNT

    You should find this article useful
    http://www.codeproject.com/cs/database/DataGridView2Db.asp


  • xinzhang

    In the end I ended up using the BindingSource_ListChanged event with the code:
    Dim Records As System.Data.DataTable = DatSet.Tables(TableName).GetChanges(RecState)
    If Not (Records Is Nothing) Then
    Try
    TbleAdapter.Update(Records)
    Catch
    If RecState = DataRowState.Modified Then
    Records = DatSet.Tables(TableName).GetChanges(DataRowState.Added)
    TbleAdapter.Update(Records)
    End If
    End Try
    DatSet.Tables(TableName).AcceptChanges()

    and it works very nicely.

    BTW the link is good but a bit hard to follow the code form non c# programmers.

  • Dogmat

    To get rid of a DataGridView extra row that is marked with an asterisk you may set AllowUserToAddRows property of a DataGridView to False. Then to add a new row you'll have to do BindingSource.AddNew().

  • Bound Datagridview: adding multiple rows and save after each add