View Full Version : VB.Net Data Grid


Uncle Gizmo
09-18-2007, 08:02 AM
This looks Interesting! (http://www.codeproject.com/useritems/Updatable_DataGridView.asp)

BukHix
09-26-2007, 09:56 AM
I think you accomplish the same thing with much less code with something like this.

Public Class Form1
Dim ds As DataSet
Private Sub GetRecords()
Dim da As SqlDataAdapter
da = New SqlDataAdapter("Select " & _
"LastName, " & _
"FirstName, " & _
"Address, " & _
"City, " & _
"State, " & _
"Zip " & _
"From CustomerData", Con)
da.TableMappings.Add("Table", "Customer")
ds = New DataSet
Try
da.Fill(ds)
ds.Tables("Customer").DefaultView.AllowNew = False
DataGridView1.DataSource = ds.Tables("Customer")
Catch ex As Exception
MessageBox.Show(ex.Message, "Data Error", MessageBoxButtons.OK)
Finally
da.Dispose()
ds.Dispose()
End Try

End Sub

Private Sub SaveRecords()
If ds.HasChanges() Then
Dim da As SqlDataAdapter = Nothing
Dim cb As SqlCommandBuilder = Nothing
da = New SqlDataAdapter("Select " & _
"LastName, " & _
"FirstName, " & _
"Address, " & _
"City, " & _
"State, " & _
"Zip " & _
"From CustomerData", Con)
da.TableMappings.Add("Table", "MeInventory")
Try
cb = New SqlCommandBuilder(da)
da.Update(ds)
Catch ex As Exception
MessageBox.Show(ex.Message, "Data Error", MessageBoxButtons.OK)
Finally
cb.Dispose()
da.Dispose()
End Try
Else
Exit Sub
End If
End Sub

You can use GetRecords() when you open the form to fill the datagrid(view) and SaveRecords() when closing or before you close the form.

Basicaly this code will save any changes to the Datagrid(view) back to the source.