Updating database from data in Gridview in VB - vb.net

This is the code for displaying data from database to gridview....If i am doing any changes in GridView and it has to update in database...I dont know how to do it...Can anyone help me....
Dim DBCONSRT, QRYSTR As String
Dim strSQL As String
Dim DBCON, myConn, myCommand, rs As Object
Dim NoOfRecords As Long
rs = CreateObject("ADODB.Recordset")
Const DB_CONNECT_STRING = "Provider=MSDASQL.1;Persist Security Info=False;User ID=cpa5k;Data Source=NP1;DSN=NP1;UID=cpa5k;PASSWORD=pass;SDSN=Default;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=QA1MM;"
myConn = CreateObject("ADODB.Connection")
myCommand = CreateObject("ADODB.Command")
myConn.Open(DB_CONNECT_STRING)
myCommand.ActiveConnection = myConn
strSQL = "select * from QA1MM.STRSK_OH FETCH FIRST 10 ROWS ONLY with ur;"
rs.Open(strSQL, myConn)
Dim myDA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
Dim myDS As DataSet = New DataSet
myDA.Fill(myDS, rs, "MyTable")
DataGridView1.DataSource = myDS.Tables(0)
DataGridView1.Refresh()
myConn.Close()
I am trying this method.but it is not working
Dim myDA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
Dim myDS As DataSet = New DataSet
myDA.Fill(myDS, rs, "MyTable")
ds = DataGridView1.DataSource
myDA.Update(ds)
I changed like this:
Dim DBCONSRT, QRYSTR As String
Dim strSQL As String
Dim DBCON, myConn, myCommand, rs As Object
Dim ds As DataSet = New DataSet
rs = CreateObject("ADODB.Recordset")
Const DB_CONNECT_STRING = "Provider=MSDASQL.1;Persist Security Info=False;User ID=cpa5k;Data Source=NP1;DSN=NP1;UID=cpa5k;PASSWORD=mexico13;SDSN=Default;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=QA1MM;"
myConn = CreateObject("ADODB.Connection")
myCommand = CreateObject("ADODB.Command")
myConn.Open(DB_CONNECT_STRING)
myCommand.ActiveConnection = myConn
Dim myDA As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter
Dim myDS As DataSet = New DataSet
Dim dtable As DataTable = New DataTable()
myDA.UpdateCommand = New SqlClient.SqlCommand("UPDATE QA1MM.STRSK_OH set OH_QTY = 10 WHERE SKU_NBR = 108011", myConn)
' myDA.UpdateCommand.Parameters.Add("#OH_QTY", OleDb.OleDbType.VarChar, 15, "OH_QTY")
' myDA.UpdateCommand.Parameters.Add("#SKU_NBR", OleDb.OleDbType.VarChar, 15, "SKU_NBR")
' myDA.UpdateCommand.Parameters(0).SourceVersion = DataRowVersion.Current
' myDA.UpdateCommand.Parameters(1).SourceVersion = DataRowVersion.Current
dtable = DataGridView1.DataSource
myDA.Update(dtable)
myConn.Close()
But it is giving error like "Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface."
I changed the connection string like:
Provider=MSDASQL.1;Persist Security Info=False;Data
Source=NP1;DSN=NP1;SDSN=Default;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Integrated
Security = True;Initial Catalog=QA1MM;
Its not working.The error is "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.".....Sorry i dont know how to change.....

You write like follow
myConn.Open(DB_CONNECT_STRING)
myDA.Update(ds.Tables(0))
myConn.Close()
EDIT:
Dont take the datasource of DataGridView1 into a dataset, instead take into a DataTable as follows
Dim dtable As New DataTable()
dtable = DataGridView1.DataSource
and update the table with DataAdapter as
myConn.Open(DB_CONNECT_STRING)
myDA.Update(dtable)
myConn.Close()
Refer to this link How to write UpdateCommand to OleDBDataAdapter

Try this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DataSet1.Tables("employee").AcceptChanges()
Dim i As Integer
Dim cmdbuilder As New OdbcCommandBuilder(odbcadptr)
i = odbcadptr.Update(odbcds, "customer")
MsgBox("Updated Rows: " & i)
End Sub

Related

Datagridview WHERE SQL Error

I'm trying to automatically fill a datagridview upon loading. This is what I have so far
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Downloads\RailwayDatabase2.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView2.DataSource = view
When I attempt this, I am met with an error reading
Cannot find table 0.
You must fill the dataset first.
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
da.Fill(ds)
Dim view As New DataView(tables(0))
This might help. Keep it simple.
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Downloads\RailwayDatabase2.accdb"
Dim MyConn As New OleDbConnection(connString)
Dim da As OleDbDataAdapter
Dim ds As DataSet
--For error handling, do this
Try
'Open the connection
MyConn.Open()
'Fill the dataset
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
ds = New DataSet
da.Fill(ds)
'Fill datagridview
DataGridView2.DataSource = ds.Tables(0)
'Close the connection
MyConn.Close()
Catch ex As Exception
'Make sure connection is closed
If MyConn.State <> ConnectionState.Closed Then MyConn.Close()
End Try
And of course, you will put second group of code in Form_Load Event.

How to configure multiple dataadapters?

The following code works ok.
Public Class DaisyServicesForm
Dim ds As DataSet = New DataSet()
Dim connStr As String = "server=inlt01\SQLEXPRESS; database=DaisyServices; integrated security=yes"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim sql As String = "SELECT t.[ID],t.[Site],t.[CLI],t.[CustomerName],t.[FromDate],t.[ToDate],t.[Quantity],t.[UnitCost],t.[TotalCost],t.[Description],t.[filenameonly],t.billingmonth as [CurrentBillingMonth], [bill] FROM [DaisyServices].[dbo].[DaisyServicesIndigo] t"
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
But for some reason when I add additional dataadapters, as per the below, I get the following error
"Object reference not set to an instance of an object."
Public Class DaisyServicesForm
Dim ds As DataSet = New DataSet()
Dim connStr As String = "server=inlt01\SQLEXPRESS; database=DaisyServices; integrated security=yes"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim sql As String = "SELECT t.[ID],t.[Site],t.[CLI],t.[CustomerName],t.[FromDate],t.[ToDate],t.[Quantity],t.[UnitCost],t.[TotalCost],t.[Description],t.[filenameonly],t.billingmonth as [CurrentBillingMonth], [bill] FROM [DaisyServices].[dbo].[DaisyServicesIndigo] t"
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim sql2 As String = "SELECT i.[ID],i.[Site],i.[CLI],i.[CustomerName],i.[FromDate],i.[ToDate],i.[Quantity],i.[UnitCost],i.[TotalCost],i.[Description],i.[filenameonly],i.billingmonth as [CurrentBillingMonth], i.[bill] From [DaisyServices].[dbo].[DaisyServicesIndigo] i LEFT JOIN [DaisyServices].[dbo].[" + TextBox1.Text + "] s on i.[SITE]=s.[SITE] AND i.[CLI]=s.[CLI] AND i.[Quantity]=s.[Quantity] AND i.[UnitCost]=s.[UnitCost] AND i.[TotalCost]=s.[TotalCost] AND i.[Description]=s.[Description] WHERE s.[CLI] is NULL"
Dim comm2 As SqlCommand = New SqlCommand(sql2, conn)
Dim dataadapter2 As SqlDataAdapter = New SqlDataAdapter(comm2)
Dim sql3 As String = "SELECT s.[ID],s.[Site],s.[CLI],s.[CustomerName],s.[FromDate],s.[ToDate],s.[Quantity],s.[UnitCost],s.[TotalCost],s.[Description],s.[filenameonly],s.billingmonth as [CurrentBillingMonth], s.[bill] From [DaisyServices].[dbo].[" + TextBox1.Text + "] s LEFT JOIN [DaisyServices].[dbo].[DaisyServicesIndigo] i on i.[SITE]=s.[SITE] AND i.[CLI]=s.[CLI] AND i.[Quantity]=s.[Quantity] AND i.[UnitCost]=s.[UnitCost] AND i.[TotalCost]=s.[TotalCost] AND i.[Description]=s.[Description] WHERE i.[CLI] is NULL"
Dim comm3 As SqlCommand = New SqlCommand(sql3, conn)
Dim dataadapter3 As SqlDataAdapter = New SqlDataAdapter(comm3)
How should I configure multiple adapters on the same form?
Thanks

Getting Data MS Access then Placing it inside VBNET texbox

i'm trying to figure out what's wrong with my code,
I'm trying to extract the value of employe ID selected from a dropdown, then get all information of that employee and place it in a textbox vb.net form, but there's a error whenever i select an employee ID
it's giving me an error message of : "An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters."
Thus highlighting reader, i'm not sure what's the problem, i have initialized the reader... Please guide me. Thanks
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
sqlQuery = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
Dim path = "Data Source= C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, Command)
con.Close()
End Sub
Private Sub QueryData(PathDb As String, command As String)
PathDb = "Data Source= C:\Databse\Company_db.accdb"
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using da As New System.Data.OleDb.OleDbCommand(command, con)
con.Open()
Dim reader = da.ExecuteReader()
If reader.Read() Then
empFnameText.Text = reader("FirstName")
empLnameText.Text = reader("LastName")
End If
con.Close()
End Using
End Using
End Sub
You need to prefix your parameter empNum with an #: #empNum. See this answer: How to pass a parameter from vb.net for an example.

Displaying data in Gridview in VB

I want to display data from database in DataGridView...This is my code...Its not working...Can anyone help me wat to do......
Dim DBCONSRT, QRYSTR As String
Dim strSQL, skunbr As String
Dim DBCON, myConn, myCommand, rs As Object
Dim NoOfRecords As Long
skunbr = TextBox1.Text
rs = CreateObject("ADODB.Recordset")
Const DB_CONNECT_STRING = "Provider=MSDASQL.1;Persist Security Info=False;User ID=cpa5k;Data Source=NP1;DSN=NP1;UID=user;PASSWORD=pass;SDSN=Default;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=QA1MM;"
myConn = CreateObject("ADODB.Connection")
myCommand = CreateObject("ADODB.Command")
myConn.Open(DB_CONNECT_STRING)
myCommand.ActiveConnection = myConn
myCommand.CommandText = "update QA1MM.STRSK_OH set OH_QTY = 250 where SKU_NBR = 100013 and STR_NBR = 116;"
myCommand.Execute()
strSQL = "select * from QA1MM.STRSK_OH where SKU_NBR = " & skunbr & " with ur FETCH FIRST 10 ROWS ONLY;"
rs.Open(strSQL, myConn)
DataGridView1.DataSource = rs
DataGridView1.Refresh()
myConn.Close()
Instead of assigning a ADODB.RecordSet directly to the datasource of datagridview like that, first convert/fill the recordset values to a dataset like below
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter
Dim myDS As DataSet = New DataSet
myDA.Fill(myDS, rs, "MyTable")
DataGridView1.DataSource = myDS.Tables(0)
DataGridView1.Refresh()
This is the classic VB way. Not .net
Please refer this MSDN link

VB.NET error adding a record to database

I'm using the code from http://homeandlearn.co.uk/NET/nets12p9.html for adding a record to the database.
It says when using a commandbuilder I should not get the error message:
Update requires a valid InsertCommand when passed DataRow collection with new rows.
However when I do the update I still get the error message. How can I fix this?
This is my code:
Dim dbProv As String
Dim dbSource As String
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
Dim Command As OleDb.OleDbCommand
Dim dr As DataRow
Dim cb As New OleDb.OleDbCommandBuilder(da)
sql = "SELECT * FROM Cliënten"
dbProv = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = [mydatabase]"
con.ConnectionString = dbProv & dbSource
con.Open()
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Cliënten")
dr = ds.Tables("Cliënten").NewRow()
dr.Item("Field1") = TextBox1.Text
dr.Item("Field2") = TextBox2.Text
ds.Tables("Cliënten").Rows.Add(dr)
da.Update(ds, "Cliënten")
MsgBox("New Record added to the Database")
con.Close()
To make da.Update() works, you must assign a valid InsertCommand, then the DataAdapter will execute it automatically. Here an example:
da.InsertCommand = New OleDb.OleDbCommand("INTERT INTO Cliënten (Field1, Field2) VALUES (#field1, #field2)")
da.InsertCommand.Parameters.Add(New OleDb.OleDbParameter("#field1", OleDb.OleDbType.VarChar, 0, "Field1"))
da.InsertCommand.Parameters.Add(New OleDb.OleDbParameter("#field2", OleDb.OleDbType.VarChar, 0, "Field2"))
da.Update(ds, "Cliënten")
WARNING: I've presumed you are using OleDb.OleDbType.VarChar for Field1 and Field2; if not you have to replace it with correct DB data format.
From what I read here it seems as though CommandBuilder should auto-generate the INSERT command for you based on the SELECT.
I think you are creating your CommandBuilder object too early - ie Before you specify the SELECT command / initialise Connection etc.
Perhaps this may work better...
Dim dbProv As String
Dim dbSource As String
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
Dim Command As OleDb.OleDbCommand
Dim dr As DataRow
sql = "SELECT * FROM Cliënten" 'Consider specifying columns
'individually rather than using *
dbProv = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = [mydatabase]"
con.ConnectionString = dbProv & dbSource
con.Open()
da = New OleDb.OleDbDataAdapter(sql, con)
Dim cb As New OleDb.OleDbCommandBuilder(da) 'Init CommandBuilder here
cb.RefreshSchema() 'This may also help
da.Fill(ds, "Cliënten")
dr = ds.Tables("Cliënten").NewRow()
dr.Item("Field1") = TextBox1.Text
dr.Item("Field2") = TextBox2.Text
ds.Tables("Cliënten").Rows.Add(dr)
da.Update(ds, "Cliënten")
MsgBox("New Record added to the Database")
con.Close()