Mark Adesina Omoniyi
Mark Adesina Omoniyi

Reputation: 449

Saving record with dataset

I want to save a record in the database using a dataset, but my data is not committing into my database.

My code can be viewed below:

Dim mydataset1 As New MyDataSet

Dim row As DataRow = mydataset1.Tables("testtable").NewRow()

With row
    .Item("name") = "Segun Omotayo"
    .Item("address") = "Abuja"
End With

mydataset1.Tables("testtable").Rows.Add(row)

Any help will be appreciated

Upvotes: 0

Views: 8328

Answers (2)

John Gathogo
John Gathogo

Reputation: 4655

I could be rusty here since its a long time since I wrote any VB.NET or used data adapters/datasets/datatables but I think if you decide to take that route you would need code like this:

Dim connection As New SqlConnection("#####YourConnectionString#####")
connection.Open()

Dim adapter As New SqlDataAdapter("SELECT * FROM testtable", connection)

' For the line below to work, you must have a primary key field in "testtable"
Dim builder As New SqlCommandBuilder(adapter)

Dim testtable As New DataTable("testtable")

adapter.Fill(testtable)

Dim row As DataRow = testtable.NewRow()

With row
    .Item("name") = "Segun Omotayo"
    .Item("address") = "Abuja"
End With

testtable.Rows.Add(row)

adapter.Update(testtable)

connection.Close()

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460168

A DataSet/DataTable is a offline/in-memory representation of your database. If you want to update the database, you need to use a DataAdapter.

For example (assuming you're using MS-Sql-Server):

Public Function UpdateDataSet(dataSet As DataSet) As Int32
    Using con = New SqlConnection(My.Settings.SqlConnection)
        Dim sql = "INSERT INTO TUser(Name,Address)VALUES(@Name,@Address)"
        Using cmd = New SqlCommand(sql, con)
            cmd.Parameters.Add(New SqlParameter("@Name", SqlDbType.VarChar))
            cmd.Parameters.Add(New SqlParameter("@Address", SqlDbType.VarChar))
            Using da = New SqlDataAdapter()
                da.InsertCommand = cmd
                con.Open()
                Dim rowCount = da.Update(dataSet)
                Return rowCount
            End Using
        End Using
    End Using
End Function

Upvotes: 1

Related Questions