How do I resolve SQL ConnectionString error? - vb.net

I have a Form with a DataGridView and a Button. They are interacting with an Access (.mdb) database. When the Button is clicked, I want it to update the data in the Table.
I get the following error:
Value of type 'OleDbConnection' cannot be converted to
'SqlConnection'.
My code:
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class Form1
Public conn As New OleDbConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim DS As New DataSet
Dim DT As New DataTable
DS.Tables.Add(DT)
Dim objConn As String = "Provider=Microsoft.JET.OLEDB.4.0; Data Source = Swiftest.mdb"
conn.ConnectionString = objConn
Dim objDA As New OleDb.OleDbDataAdapter("SELECT * FROM tblOptions", conn)
objDA.Fill(DT)
DataGridView1.DataSource = DT.DefaultView
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SqlQuery As String = "'UPDATE tblOptions Set fldShow = '1' WHERE fldID = '13'"
conn.Open()
Dim com As New SqlCommand(SqlQuery, conn)
End Sub
End Class
Thanks for reading

Several of the database objects available is ADO.net have .Dispose methods. If an object has a dispose method it may be using unmanaged resources (resources outside the .net framework). These objects need to release these resources and they do this in there dispose methods. Fortunately the .net languages provide Using...End Using blocks which will guarentee that .Dispose is called even if there is an error.
In view of this create your database objects in the Sub or Function where they are used so they can be enclosed in Using blocks. Note the comma at the end of the connection Using line. This indicates that the object on the next line (the command) is included in the same Using block.
In your Form.Load event, you never used the adapter or the dataset. Just load the datatable.
Open the connection at the last possible moment, directly before the .Execute... and close immediately with the End Using. In your Button1.Click event you open a connection, never execute anything and never close it.
In your update command you provide literals as String. Normally, an ID field is an Integer. Check you database for the datatype of the fields. If you want to provide values that are not literals use parameters.
Private connStr As String = "Provider=Microsoft.JET.OLEDB.4.0; Data Source = Swiftest.mdb"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim DT As New DataTable
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand("SELECT * FROM tblOptions", conn)
conn.Open()
Using reader = cmd.ExecuteReader
DT.Load(reader)
End Using
End Using
DataGridView1.DataSource = DT.DefaultView
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand("UPDATE tblOptions Set fldShow = '1' WHERE fldID = '13'", conn)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

Related

Insert, Delete, and Edit Data in DataGridView using single Update Button in Vb.net

I am trying to have a add, delete, and edit function in Vb.net by using one update button and changing the values in the datagridview manually then hitting update. However, I get an error stating
"System.InvalidOperationException: 'Update requires a valid UpdateCommand when passed DataRow collection with modified"
Any Ideas? The error comes next to the da.Update(changes)
Also in the above code not shown in my code I have load_data() in the private form1_load sub.
Here is code:
Dim da As New SqlDataAdapter
Dim dt As New DataSet
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim cmd As New SqlCommandBuilder
Dim changes As New DataSet
changes = dt.GetChanges
If changes IsNot Nothing Then
da.Update(changes)
da.Fill(dt)
DataGridView1.DataSource = dt.Tables(0)
End If
End Sub
Private Sub load_data()
Using connection = New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=vbconnectionfinal;Integrated Security=True")
da = New SqlDataAdapter("Select * From TrueTrack", connection)
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt.Tables(0)
End Using
End Sub
You are creating a SqlCommandBuilder but not associating it with a SqlDataAdapter, so what's the point? The whole purpose of a command builder is to automatically generate action commands when you call Update on a data adapter. When you create your data adapter, create the command builder immediately after and associate the two, which you would do by passing the data adapter as an argument to the constructor of the command builder.
The following code works for me.
Dim da As New SqlDataAdapter
Dim dt As New DataSet
Dim connection = New SqlConnection("connection string")
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cmd As New SqlCommandBuilder(da)
Dim changes As New DataSet
changes = dt.GetChanges
If changes IsNot Nothing Then
da.Update(changes)
DataGridView1.DataSource = dt.Tables(0)
End If
End Sub
Private Sub load_data()
Dim cmd As SqlCommand = New SqlCommand("Select * From TrueTrack", connection)
da = New SqlDataAdapter(cmd)
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt.Tables(0)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
load_data()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
connection.Close()
End Sub

How to display multiple results from a users' input from filters using MS Access and Visual Basic

I'm struggling to grasp VB as I'm new to programming. I am creating a program which displays a result (namely a link to a website) based on a users' filters. I've done this so far, which just selects the size filter. However, I don't know how to write the code that will check the database for the users' preference and output an appropriate link in the form of a label. Is it as simple as just printing DataTable or am I totally wrong? Any help would be greatly appreciated.
Here is my code so far:
Imports System.Data.OleDb
Public Class frmFilters
Dim provider As String
Dim dataFile As String
Dim ConnString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private ConStr As String = "My Connection String"
Private Sub buttonSearch_Click(sender As Object, e As EventArgs) Handles buttonSearch.Click
provider = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "H:\Visual studio files\Project\CMPC\partLists.accdb"
End Sub
Private Function GetPartData(filterMicroATX As Integer, filterATX As Integer) As DataTable
Dim dt As New DataTable
Dim sql = "SELECT * FROM partList WHERE
[size] > #MicroATX
And [size] < #ATX;"
Using con As New OleDbConnection(ConStr),
cmd As New OleDbCommand(sql, con)
With cmd.Parameters
.Add("#MicroATX", OleDbType.Integer).Value = filterMicroATX
.Add("#ATX", OleDbType.Integer).Value = filterATX
End With
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub btnQuit_Click(sender As Object, e As EventArgs) Handles btnQuit.Click
Me.Close()
End Sub
End Class

Unable to save from DataGridView to SQL Server Database VB.Net

My Data from database displays successfully to DataGridView but When i make changes in DataGridView and click the update button in the form code executes successfully and show message "update successfully"...That Means code is working properly but the problem is changes was not being saved in database...when i reload the form, it shows the old data no any changes...Here is my code
Imports System.Data.SqlClient
Public Class FormUpdate
'Variables declared here
Dim Con As New SqlConnection
Dim Cmd As New SqlCommand
Dim ds As DataSet
Dim da As New SqlDataAdapter
Dim cmdString As String
Dim dt As New DataTable
Dim dr As SqlDataReader
Dim cmdbl As New SqlCommandBuilder
Public Sub FormUpdate_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'ShipmentDataSetDataGridView.Shipment_Main' table. You can move, or remove it, as needed.
Me.Shipment_MainTableAdapter2.Fill(Me.ShipmentDataSetDataGridView.Shipment_Main)
'CONNECTION STRING FOR THE DATABASE
Con.ConnectionString = "Data Source=TARIQUE;Initial Catalog=shipment;Integrated Security=True"
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Try
Con.Open()
cmdbl = New SqlCommandBuilder(da)
da.Update(dt)
MessageBox.Show("Updated successfully!")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Con.Close()
End Sub
End Class
I think you have missed the GetUpdateCommand().Update method fails if this line of code is missed.
try adding cmdb1.GetUpdateCommand() before da.Update(dt).
hope it helps.

How To Populate a DropDown List From a DataSet?

I am trying to populate an ASP dropdown list in vb.net with the results from a stored procedure returned in a data set. I was wondering if anyone knew the vb.net code to populate the dropdown list?
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim connString As String = "Server=MYCOMPUTER\SQLEXPRESS;Database=scales;Trusted_Connection=True"
Dim myConn As New SqlConnection(connString)
myConn.Open()
Dim da As New SqlDataAdapter("select scaleName from scales", myConn)
Dim dt As New DataTable
da.Fill(dt)
ComboBox1.DisplayMember = "scaleName"
ComboBox1.DataSource = dt
myConn.Close()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
IF Not IsPostback then
PopulateDropdown()
End IF
End Sub
Private Sub PopulateDropDown()
Dim connString As String = "Server=MYCOMPUTER\SQLEXPRESS;Database=scales;Trusted_Connection=True"
Dim myConn As New SqlConnection(connString)
myConn.Open()
Dim da As New SqlDataAdapter("select ScaleId, scaleName from scales", myConn)
Dim dt As New DataTable
da.Fill(dt)
Me.ComboBox1.DataTextField = "scaleName "
Me.ComboBox1.DataValueField = "ScaleId"
Me.ComboBox1.DataSource = dt
Me.ComboBox1.DataSourceID = String.Empty
Me.ComboBox1.DataBind()
myConn.Close()
End Sub
In order to show the data in the DropDownList control, you can use the following Code. To use the results of a Stored Procedure, you need to create the SELECT command:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim dt As New DataTable
Dim connString As String = "Server=MYCOMPUTER\SQLEXPRESS;Database=scales;Trusted_Connection=True"
Using myConn As New SqlConnection(connString)
myConn.Open()
Using cmd = myConn.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "dbo.uspMyStoredProc"
cmd.Parameters.AddWithValue("#MyInputParam", 123)
Using da As New SqlDataAdapter(cmd)
da.Fill(dt)
End Using
End Using
End Using
ComboBox1.DisplayMember = "scaleName"
ComboBox1.DataSource = dt
ComboBox1.DataBind()
End If
' ...
End Sub
I've adjusted the following things:
Usually you only need to bind the data on the initial request. Therefore, the if statement at the beginning checks the IsPostBack property.
In order to close and dispose the connection and the data datapter reliably, I've added some using statements.
In order to access the stored procedure, I've created a SqlCommand and set the CommandType to StoredProcedure. The CommandText is set to the name of the Stored Procedure. In the sample, I've also added a parameter named MyInputParam that is sent to the Stored Procedure.

VB.NET 2008 DataGridView not Updating Visual Foxpro Database

I'm using VB.NET 2008 with a DataGridView and I'm interfacing to a Visual Foxpro 6 database using the vfpoledb.1 driver. When I change a value in the description field, it changes in the DataGridView but the database never gets updated. Do I need to use code to force the changes to take place?
Here's the code I'm using:
Imports System.Data.OleDb
Public Class Form1
Dim sConString As String = "Provider=vfpoledb.1;Data Source=C:\MyDatabase.dbc;Mode=3;"
Dim con As OleDbConnection = New OleDbConnection(sConString)
Private Function FetchData()
con.Open()
Dim ds As DataSet = New DataSet()
Dim sSQL As String
sSQL = "SELECT item_cd, item_desc FROM invent;"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, con)
Dim daInv As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim iRecCount As Integer
iRecCount = daInv.Fill(ds, "invent")
Me.DataGridView1.DataSource = ds.Tables("invent").DefaultView
End Function
Private Sub btnFetchData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFetchData.Click
Call FetchData()
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
con.Close()
con = Nothing
End Sub
End Class
Did this code will update the Table and push the changes back to Database? I don't think so. I tried the same code with SQL Server 2005, and it is not working(I don't have a FoxPro db). So I modified the code and now it is working fine.
Imports System.Data.OleDb
Public Class Form1
Dim sConString As String = "Provider=vfpoledb.1;Data Source=C:\MyDatabase.dbc;Mode=3;"
Dim con As OleDbConnection = New OleDbConnection(sConString)
Dim daInv As OleDbDataAdapter
Dim ds As DataSet = New DataSet()
Private Sub FetchData()
con.Open()
Dim sSQL As String
sSQL = "SELECT item_cd, item_desc FROM invent;"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, con)
daInv = New OleDbDataAdapter(cmd)
Dim builder As New OleDbCommandBuilder(daInv)
Dim iRecCount As Integer
iRecCount = daInv.Fill(ds, "invent")
Me.DataGridView1.DataSource = ds.Tables("invent").DefaultView
End Sub
Private Sub btnFetchData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFetchData.Click
Call FetchData()
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs)
daInv.Update(ds.Tables("invent"))
con.Close()
con = Nothing
End Sub
End Class
Hope it works :)
I found the underyling problem and resolved it. The VFP table I'm accessing does not have a primary key defined. It does have indexes but they are simply marked as "Regular" indexes (using VFP terminology).
I was able to use a VFP tool call vRunFox (Visual Run Fox) from Ed Leafe's website to modify the table structure. I had to use some VFP commands to bring up the Table Designer window.
I also had to add some code to my FormClosing event. Here's what my FormClosing event looks like now:
Dim myBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(daInv)
myBuilder.GetUpdateCommand()
daInv.UpdateCommand = myBuilder.GetUpdateCommand
daInv.Update(ds.Tables("invent"))
con.Close()
con = Nothing