Writing a DataGridView contents to SQL via Dataset

Another one that took considerable time to find and answer for.

As for the last post, I have a DataGridView that does not allow the user to add or delete rows via the grid.

They can however use a button on the form to add or delete. Add creates a new row in the base dataset which shows the bland row on the grid.

Dim row As DataRow = dsCountries.Tables("Country").NewRow
row.Item("pkCountryID") = 0
row.Item("Country") = String.Empty

dsCountries.Tables("Country").Rows.Add(row)

Dim LastRow As Integer = grdCountries.Rows.GetLastRow(DataGridViewElementStates.Visible)
grdCountries.Rows(LastRow).Cells.Item("Country").Selected = True
grdCountries.BeginEdit(True)


The grid is bound to a binding source:

Private WithEvents bs As BindingSource

bs = New BindingSource(dsCountries.Tables(0), String.Empty)

grdCountries.DataSource = dsCountries.Tables("Country")


Then the ListChanged event is tested on the binding source to know when to update the data to the database:

Private Sub bs_ListChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ListChangedEventArgs) _
Handles bs.ListChanged

UpdateCountries(dsCountries)

End Sub


The delete button simply handles the OnClick event for the button:

Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

If Me.grdCountries.SelectedCells.Count > 0 Then

Me.grdCountries.Rows.RemoveAt( _
Me.grdCountries.SelectedCells(0).RowIndex)

UpdateCountries(dsCountries)

End If

End Sub


Hopefully I don't need to go looking for this stuff again...


Posted: 31. October 2006 15:35 by cutty
Categories: ASP.Net Coding Hints and Tips | SQL Server Tags: ,
Comments are closed