Domanda

I'm trying to define a datarow to hold values and then add it to data set indgv: datagridview with values in it dsdetails: a dataset with a table named details

If indgv.Rows.Count > 0 Then
            Dim dr As DataRow
            dr = dsdetails.Tables("details").NewRow
            For Each row As DataGridViewRow In indgv.Rows
                dr("mat") = row.Cells("icode").Value
                dr("dateoftrans") = Me.DateTimePicker1.Value
                dr("numoftrans") = transnum.Text
                dr("type") = 1
                dr("doc") = doctyp.SelectedValue
                dr("amount") = row.Cells("iamo").Value
                dsdetails.Tables("details").Rows.Add(dr)
            Next
            adpdetails.Update(dsdetails, "details")
        End If

running this causes the following error

Object reference not set to an instance of an object.

how to rephrase the declaration with 'New' to avoid the problen BTW : when using new as the following

Dim dr As New DataRow = dsdetails.Tables("details").NewRow

it shows design time error

Type 'dsdetails.Tables' is not defined.

È stato utile?

Soluzione

Try this code:

If indgv.Rows.Count > 0 Then

    Dim tbl As DataTable = dsdetails.Tables("details")
    Dim dr As DataRow

    For Each row As DataGridViewRow In indgv.Rows

        dr = tbl.NewRow 'Create a new row inside the loop!
        dr("mat") = row.Cells("icode").Value
        dr("dateoftrans") = Me.DateTimePicker1.Value
        dr("numoftrans") = transnum.Text
        dr("type") = 1
        dr("doc") = doctyp.SelectedValue
        dr("amount") = row.Cells("iamo").Value

        tbl.Rows.Add(dr)

    Next

    adpdetails.Update(tbl)

End If

Altri suggerimenti

If all you need is to copy rows from one table to another, DataTable class has a Copy method you may want to use. It works like this:

Dim dtCopy As New DataTable()
dtCopy = dt.Copy()

If you have a datagridview control bound to a table, you could also use this form:

Dim dtCopy As New DataTable()
dtCopy = DirectCast(dataGridViewX1.DataSource, DataTable).Copy()

The Copy method will copy the datatable structure and the data. If you want to copy the structure only without the data you could use Clone method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top