Converting from DataGridView to DataSet
Posted on 2011-04-22
Hi - In my app, user enters a parent record - slip_id, job_id, etc.
There are 4 datagridviews that then contain data "linked" back to the this parent record.
The construct the DGV's manually via code.
When the user goes to save the entire slip, I'm trying to convert each of them to a dataset but I have an issue:
- When the user enters the DGV and begins to enter data, there is a second row created below....how can I stop this from happening? I only want to see one row at a time.
There are columns in the DGV that are hidden, and I populate them behind the scenes. So when this second row is created, I populate the cells with data from the "parent" record, but the other values are null. Based on my code, it forces me to add a row with a bunch of nulls to the dataset.
Here is the code I'm using to convert from datagrid....
Public Function DG_TO_Dataset(ByVal dgv As DataGridView) As DataSet
Dim ds As New DataSet
'Add a new table to the dataset
'Add the columns
Dim col As DataColumn
'For each colum in the datagridveiw add a new column to your table
For Each dgvCol As DataGridViewColumn In dgv.Columns
col = New DataColumn(dgvCol.Name)
'Add the rows from the datagridview
Dim row As DataRow
Dim colcount As Integer = dgv.Columns.Count - 1
For i As Integer = 0 To dgv.Rows.Count - 1
row = ds.Tables("Table").Rows.Add
For Each column As DataGridViewColumn In dgv.Columns
row.Item(column.Index) = dgv.Rows(i).Cells(column.Index).Value
Catch ex As Exception
'Catch any potential errors and display them to the user
MessageBox.Show("Error Converting from DataGridView" & ex.InnerException.ToString, _
"Error Converting from DataGridView", MessageBoxButtons.OK, MessageBoxIcon.Error)