How to append data imported from excel to a bound datagridview vb and save it to the SQL table?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi All,
Im using this snippet to import data to a bound datagridview. I suceed to import data into datagridview but the original data in the datagridview disappear. What it want is to append the imported data to the existing one in the datagridview. How can I change this snippet to append data?
Private Sub ToolStripButton1_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton1.Click
Dim opendlg As New OpenFileDialog
opendlg.Filter = "Excel Files (*.xls)|*.xls|All Files (*.*)|*.*"
If opendlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim pathname As String = opendlg.FileName
connect = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;" & "data source=" & pathname & ";Extended Properties=Excel 8.0;")
adapter = New System.Data.OleDb.OleDbDataAdapter("select * from [Foglio1$]", connect)
connect.Open()
adapter.Fill(dataset)
CaricoCampioniDataGridView.DataSource = dataset.Tables(0)
connect.Close()
CaricoCampioniDataGridView.Refresh()
End If
End Sub

For saving Im using this snippet but the following error "Reference to an object not set on an object instance" prevent me to successfully save. Where is the error?
Dim workrow As DataRow
Dim i As Integer
For i = 0 To CaricoCampioniDataGridView.Rows.Count - 2
workrow = CaricoCampioniDataSet.Tables("mytable").NewRow()
workrow(0) = CaricoCampioniDataGridView.Rows(i).Cells(0).Value if the table field is a string
workrow(1) = Val(CaricoCampioniDataGridView.Rows(i).Cells(0).Value) if the table field is a number
CaricoCampioniDataSet.Tables("mytable").Rows.Add(workrow)
Next
Me.TableAdapterManager.UpdateAll(Me.CaricoCampioniDataSet)

Thank All, your help is appreciated.

View the full article
 
Back
Top