SqlDataAdapter not working - vb.net

I'm trying to update a database using the SqlDataAdapter but my code does not seem to work:
Dim sitedb As String = BookingApp.Globals.siteDB
Dim conn As New SqlConnection(sitedb)
Dim sql As String = "select * from name where BOOKING_REF = 'H2124'"
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim cb As SqlCommandBuilder
Dim dt As New DataTable
Dim c As Integer
cmd = New SqlCommand(sql, conn)
da = New SqlDataAdapter(cmd)
cb = New SqlCommandBuilder(da)
da.Fill(dt)
For c = 0 To dt.Rows.Count - 1
dt.Rows(c)!OVLREF3 = c
dt.AcceptChanges()
Next
da.Update(dt)
As far as I can see the code seems to look okay, anyone got any suggestions?
Thanks

Remove dt.AcceptChanges and it should work.
AcceptChanges will change the RowState to Unchanged, that causes the DataAdapter to do nothing. AcceptChanges is called implicitely by the DataAdapter itself after the update.

Related

How to call the datatable fill code without double in vb.net

How to call the datatable fill code without double in vb.net?.
in the code below you might see I wrote back the fill datatable code if there is a solution without me writing it back in "GenerateReport()". Please Recommend.
Thanks
Private WithEvents dt As New DataTable
Public Sub fillDataGridView1()
dt = New DataTable
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
da.Dispose()
Dim totalColumn As New DataColumn()
totalColumn.DataType = System.Type.GetType("System.Double")
totalColumn.ColumnName = "Total"
totalColumn.Expression = "[CIA]*[QTY]*(1-[DPR]/100)"
dt.Columns.Add(totalColumn)
Me.grid.DataSource = dt
Me.grid.Refresh()
End Using
End Using
End Using
End Sub
Private Sub GenerateReport()
KtReport1.Clear()
'the code below actually already exists but I reuse it
dt = New DataTable
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
Dim dtCloned As DataTable = dt.Clone()
dtCloned.Columns("CIA").DataType = GetType(String)
For Each row As DataRow In dt.Rows
dtCloned.ImportRow(row)
Next row
KtReport1.AddDataTable(dtCloned)
The issue is that you are essentially duplicating code despite the fact that you have a variable setup to hold the filled DataTable at the Form level.
What I would suggest doing is creating a function that returns the filled DataTable, then at the top of your two existing methods do a null check against the Form level variable.
Take a look at this example:
Private _dt As DataTable
Private Function GetAndFillDataTable() As DataTable
Dim dt As New DataTable()
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
da.Dispose()
Dim totalColumn As New DataColumn()
totalColumn.DataType = System.Type.GetType("System.Double")
totalColumn.ColumnName = "Total"
totalColumn.Expression = "[CIA]*[QTY]*(1-[DPR]/100)"
dt.Columns.Add(totalColumn)
Return dt
End Using
End Using
End Using
End Function
Private Sub FillDataGridView1()
If (_dt Is Nothing) Then
_dt = GetAndFillDataTable()
End If
grid.DataSource = _dt
grid.Refresh()
End Sub
Private Sub GenerateReport()
If (_dt Is Nothing) Then
_dt = GetAndFillDataTable()
End If
Dim dtCloned As DataTable = _dt.Clone()
dtCloned.Columns("CIA").DataType = GetType(String)
For Each row In _dt.Rows
dtCloned.ImportRow(row)
Next row
KtReport1.AddDataTable(dtCloned)
End Sub

Select from sql in vb and display in aspx page

Just wanna select a word from database and display in aspx page
Backend
Using da As New SqlDataAdapter
con.Open()
cmd.CommandText = "SELECT value_en as value FROM tbl_language WHERE element_id = 'a1';"
da.SelectCommand = cmd
Dim dt As New DataTable
da.Fill(dt)
Dim WordValue As String = dt.Rows(0).Item(0)
End Using
in aspx page
<%=WordValue%>
whats wrong here?
Assign Connection to the command object and also convert item(0) into string
Using da As New SqlDataAdapter
con.Open()
cmd.CommandText = "SELECT value_en as value FROM tbl_language WHERE element_id = 'a1';"
cmd.Connection =con
da.SelectCommand = cmd
Dim dt As New DataTable
da.Fill(dt)
Dim WordValue As String = Convert.ToString(dt.Rows(0).Item(0))
End Using
or
Using da As New SqlDataAdapter( "SELECT value_en as value FROM tbl_language WHERE element_id = 'a1';",con)
Dim dt As New DataTable
da.Fill(dt)
Dim WordValue As String = Convert.ToString(dt.Rows(0).Item(0))
End Using

DataSet update error requires InsertCommand

Trying to add a row to an Access 2010 database with VB 2013. Everything seems to work until the UPDATE statement when I get this error:
Update requires a valid InsertCommand when passed DataRow collection with new rows.
My code is:
Dim sqlConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\CLI_CRVM.accdb")
Dim cmd As New System.Data.OleDb.OleDbCommand()
Dim ds As New DataSet1()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "SELECT * FROM [extract] ;"
cmd.Connection = sqlConnection
sqlConnection.Open()
Dim da = New OleDb.OleDbDataAdapter(cmd.CommandText, sqlConnection)
da.Fill(ds, "extract")
ds.Clear()
Dim newExtractRow As DataRow = ds.Tables("extract").NewRow()
newExtractRow("Field1") = "ABC123"
ds.Tables("Extract").Rows.Add(newExtractRow)
da.Update(ds, "Extract")
sqlConnection.Close()
Everything I've found so far seems to reference an SQL database, not OleDb connection.
You can probably use an OleDbCommandBuilder, like so
' your existing OleDbDataAdapter
Dim da = New OleDb.OleDbDataAdapter(cmd.CommandText, sqlConnection)
' add the following lines:
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
For details, see
OleDbCommandBuilder Class
Working Example
For an Access table named extract with fields
ID - AutoNumber, Primary Key
Field1 - Text(255)
and data
ID Field1
-- -------
1 TEST999
the following VB.NET code will insert a second row into the table in the Access database
Using con As New OleDbConnection
con.ConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=C:\Users\Public\Database1.accdb;"
con.Open()
Using da As New OleDbDataAdapter("SELECT * FROM [extract]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Dim dt = New DataTable
da.Fill(dt)
Dim dr As DataRow = dt.NewRow
dr("Field1") = "ABC123"
dt.Rows.Add(dr)
da.Update(dt)
End Using
con.Close()
End Using
with the result
ID Field1
-- -------
1 TEST999
2 ABC123
The OleDbCommandBuilder object automatically (and invisibly) creates the INSERT, UPDATE, and DELETE commands based on the SELECT command that was supplied when the OleDbDataAdapter object was created.
You need to set the InsertCommand property
Dim da = New OleDb.OleDbDataAdapter(cmd.CommandText, sqlConnection)
da.InsertCommand = cmd
da.Fill(ds, "extract")
More info here

reportview using sqldataadapter

is there a way to make a reportviewer using sqldataadapter? is it possible?
It seems that I can't find a way to get it on datasource.
Dim con As SqlConnection = New SqlConnection("Data Source = pc11-pc\kim; Initial Catalog = mypos; User ID = sa; Password = 123")
Dim sqlstr As String = "Select * from Supplier"
Dim adp As SqlDataAdapter = New SqlDataAdapter(sqlstr, con)
Dim dt As New DataTable
adp.Fill(dt)
'reportviewer1.datasources = dt
Here's the glimps of it...
Dim dt As DataTable = New DataTable
Dim conn As SqlConnection = New SqlConnection(connString)
Try
conn.Open()
Dim cmd As New SqlCommand(sql, conn)
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(dt)
Catch ex As Exception
MessageBox.Show("Error")
Finally
conn.Close()
End Try
Dim ds As New ReportDataSource(dataSourceName, dt)
rViewer.LocalReport.DataSources.Clear()
rViewer.LocalReport.DataSources.Add(ds)
rViewer.LocalReport.Refresh()
here's my code sir
'TODO: This line of code loads data into the 'myposDataSet5.Product' table. You can move, or remove it, as needed.
Me.ProductTableAdapter.Fill(Me.myposDataSet5.Product)
Dim dt As DataTable = New DataTable
Dim conn As SqlConnection = New SqlConnection("Data Source = pc11-pc\kim; Initial Catalog = mypos; User ID = sa; Password = 123")
Try
conn.Open()
Dim cmd As New SqlCommand("Select * From Product", conn)
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(dt)
Catch ex As Exception
MessageBox.Show("Error")
Finally
conn.Close()
End Try
'Dim ReportDataSource As DataTable = New DataTable
'Dim ds As New ReportDataSource(dt.TableName = "test", dt)
Dim ds As New Microsoft.Reporting.WinForms.ReportDataSource(dt.TableName, dt)
ReportViewer1.LocalReport.ReportPath = "D:\visual studio\mypos\mypos\Report3.rdlc"
ReportViewer1.LocalReport.DataSources.Clear()
ReportViewer1.LocalReport.DataSources.Add(ds)
ReportViewer1.LocalReport.Refresh()
Me.ReportViewer1.RefreshReport()

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
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
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()