Search code examples
vb.netvisual-studio-2012datagridviewdatatable

Store datagridview into datarow


I want to store the values the values held in a DatagridView and store them in a DataTable. I am using the following code but what I am doing wrong as it is not moving it to the DataTable?

   Dim dt As New DataTable, ds As New DataSet

        Dim updatelist As String = String.Empty
        For i As Integer = 0 To dgvSteak.Rows.Count - 1
            updatelist = dgvSteak.CurrentRow.Index


            Dim newSteakRow As DataRow = ds.Tables("Steak").NewRow()

            newSteakRow("STEAK_ID") = dgvSteak.Item("Steak_ID", i).Value
            newSteakRow("STEAK_Name") = dgvSteak.Item("Steak_Name", i).Value

            ds.Tables("Steak").Rows.Add(newSteakRow)

        Next

Solution

  • This is what I use to copy a datagridview to a datatable and it seems to work. So datatable row 2, columns 4 will have the same value as datagridview row 2, columns 4, and so on.

        Dim datatable1 As New DataTable
        Dim a, b As Integer
    
        ' make the datatable rows and columns match the datagridview
        a = 0
        Do While a < Me.DataGridView1.ColumnCount
            datatable1.Columns.Add()
            a += 1
        Loop
        a = 0
        Do While a < Me.DataGridView1.RowCount
            datatable1.Rows.Add()
            a += 1
        Loop
    
        ' add datagridview values to datatable
        a = 0
        Do While a < Me.DataGridView1.ColumnCount
            b = 0
            Do While b < Me.DataGridView1.RowCount
                datatable1.Rows(a).item(b) = Me.DataGridView1.Rows(a).cells(b).value
                b += 1
            Loop
            a += 1
        Loop