How to declare a connection object on a class level connection not in local scope with VB.NET? - sql-server

I got the error:
Fill: SelectCommand.Connection property has not been initialized.
I think this is because I declare my data set not inside the private sub but in the public class.....
but I need to use the data set in more than once in different private sub during the program....how should I define it ?
many thanks.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Dim strsql As String
Dim da As New SqlDataAdapter(strsql, con)
Dim ds As New DataSet()
Dim strcon As String
Dim newmode As Boolean
Dim newrow As DataRow
Dim cb As SqlCommandBuilder
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
newmode = False
'Dim con As SqlConnection
'Dim strsql As String
con = New SqlConnection("initial catalog=test;data source=nazi;integrated security=sspi;")
strsql = "select*from table_1"
con.Open()
'Dim da As New SqlDataAdapter(strsql, con)
'Dim ds As New DataSet()
da.Fill(ds, "dd")
TextBox1.DataBindings.Add(New Binding("text", ds, "dd.tel"))
TextBox2.DataBindings.Add(New Binding("text", ds, "dd.nam"))
TextBox3.DataBindings.Add(New Binding("text", ds, "dd.address"))
da.update(ds, "dd")
con.Close()
End Sub
Private Sub empty()
textrecord.text = ""
TextBox1.text = ""
TextBox2.text = ""
TextBox3.text = ""
TextBox4.text = ""
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
newrow = ds.Tables("dd").NewRow
newmode = True
textrecord.BackColor = Color.Red
textrecord.Text = "new record"
MsgBox("enter new record and press save")
Call empty()
End Sub
End Class

Instead of:
Dim con As SqlConnection
try adding New:
Dim con As New SqlConnection("initial catalog=test;...")
However, it's best practice to only open a connection just before you need it, and close it right after. Connections should be local variables in Using blocks, not class variables!

You create the DataAdapter at the global level in this line
Dim da As New SqlDataAdapter(strsql, con)
but at this point in time your strsql is empty and if you change it afterwards it doesn't change inside the dataadatpter, thus the error message.
If you insist on keeping all that global vars (and it's considered a bad practice as #Andomar pointed out in is answer) then you should be sure to create the DataAdapter with the correct sqlstring just before its usage:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
newmode = False
con = New SqlConnection("initial catalog=test;data source=nazi;integrated security=sspi;")
strsql = "select*from table_1"
con.Open()
da = New SqlDataAdapter(strsql, con) '<- added this line here '
da.Fill(ds, "dd")
....
con.Close()
End Sub

Related

If statement to not allow insert statement to work because a cell is null

I want the code to not allow the complete button to work because the column of "StartTime" is null.
Attached is the code below:
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Public Class Etask
Dim con As SqlConnection
Dim cmd As SqlCommand
Private Sub Etask_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Labelname.Text = login.mname
Dim str As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
Dim con As New SqlConnection(str)
Dim com As String = "SELECT TaskID, Name, TaskAssigned, StartTime, FinishTime, Status
FROM dbo.Tasks
WHERE Name = '" & Labelname.Text & "'"
Dim Adpt As New SqlDataAdapter(com, con)
Dim ds As New DataSet()
Adpt.Fill(ds, "PosTable")
DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Sub Etask_Resize(sender As Object, e As EventArgs) Handles Me.Resize
Panel1.Left = (Me.Width - Panel1.Width) / 2
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
refreshDGV()
End Sub
Public Sub refreshDGV()
Labelname.Text = login.mname
Dim str As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
Dim con As New SqlConnection(str)
Dim com As String = "SELECT TaskID, Name, TaskAssigned, StartTime, FinishTime, Status
FROM dbo.Tasks
WHERE Name = '" & Labelname.Text & "'"
Dim Adpt As New SqlDataAdapter(com, con)
Dim ds As New DataSet()
Adpt.Fill(ds, "PosTable")
DataGridView1.DataSource = ds.Tables(0)
End Sub
'complete button
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection("Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true")
Dim query As String = "update Tasks set FinishTime=#FinishTime,Status=#Status where TaskID=#id"
con.Open()
cmd = New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#FinishTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = comboboxstatus.Text
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Successfully updated!")
refreshDGV()
End Sub
Private Sub FillByToolStripButton_Click(sender As Object, e As EventArgs)
Try
Me.TasksTableAdapter.FillBy(Me.RestaurantDatabaseDataSet2.Tasks)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Me.LabelID.Text = DataGridView1.Item(0, i).Value
End Sub
Private Sub btnstart_Click(sender As Object, e As EventArgs) Handles btnstart.Click
Dim con As New SqlConnection("Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true")
Dim query As String = "update Tasks set StartTime=#StartTime,Status=#Status where TaskID=#id"
con.Open()
cmd = New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#StartTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = "Working on it!"
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Successfully started!")
refreshDGV()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = Date.Now.ToString("dd MMM yyyy hh:mm:ss")
End Sub
End Class
This is what the application looks like:
I want the code to check for null data in the StartTime column. If its null, then the complete button won't work. Button1 is the button to complete a task.
ExecuteNonQuery returns an integer with the number of rows affected.
If you create the query so that it does not do an update if the column is NULL, then it will return 0, which you can check for.
Also, it is easier to put the connection string in just one place, so that if you need to change it you only have to do so once - it is too easy to miss an occurrence of the string and have to go and edit it again. Often, such data is stored in the settings for the program, but I've made it as a constant for this example:
Public Const CONNSTR As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
'....
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query As String = "UPDATE Tasks
SET FinishTime = #FinishTime, Status = #Status
WHERE TaskID = #id
AND StartTime IS NOT NULL"
Dim nRowsAffected = 0
Using con As New SqlConnection(CONNSTR),
cmd As New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#FinishTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = comboboxstatus.Text
con.Open()
nRowsAffected = cmd.ExecuteNonQuery()
End Using
If nRowsAffected = 0 Then
MsgBox("Database not updated - check for empty StartTime.")
Else
MsgBox("Successfully updated!")
End If
refreshDGV()
End Sub
The Using statement makes sure that "unmanaged resources" are released when it is done.

Search by Image with SQL Server database and VB

I am tired to make the search engine to run. Just I want to make search by image in my SQL Server database by making a choice of the column with same image.
I tried to make it with this code:
cmd = New SqlCommand("select * from TBL_Image Where Image = " & Image, sqlcon)
Can anyone help me?
Picture of Project
This is my code
Imports System.Data.SqlClient
Imports System.IO
Imports System.Drawing.Image
Public Class Form1
Dim sqlcon As New SqlConnection("server=.\MOHAMED; database=DB_Image;
integrated security = true")
Dim cmd As SqlCommand
Sub selectImage(ByVal Image As Image)
cmd = New SqlCommand("select * from TBL_Image Where Image = " & Image, sqlcon)
sqlcon.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
dr.Read()
txtShow.Text = dr(0)
Dim sora2() As Byte = CType(dr(1), Byte())
Dim ms2 As New MemoryStream(sora2)
pbox3.Image = Image.FromStream(ms2)
dr.Read()
Dim sora3() As Byte = CType(dr(1), Byte())
Dim ms3 As New MemoryStream(sora3)
pbox4.Image = Image.FromStream(ms3)
dr.Read()
Dim sora4() As Byte = CType(dr(1), Byte())
Dim ms4 As New MemoryStream(sora4)
pbox5.Image = Image.FromStream(ms4)
dr.Read()
Dim sora5() As Byte = CType(dr(1), Byte())
Dim ms5 As New MemoryStream(sora5)
pbox6.Image = Image.FromStream(ms5)
dr.Read()
Dim sora6() As Byte = CType(dr(1), Byte())
Dim ms6 As New MemoryStream(sora6)
pbox7.Image = Image.FromStream(ms6)
dr.Read()
Dim sora7() As Byte = CType(dr(1), Byte())
Dim ms7 As New MemoryStream(sora7)
pbox8.Image = Image.FromStream(ms7)
sqlcon.Close()
dr.Close()
End Sub
Private Sub btnBrowse1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse1.Click
ofd1.Filter = "All Images |*.PNG; *.JPG; *.BMP; *.GIF; *.JPEG"
If ofd1.ShowDialog = DialogResult.OK Then
pbox1.Image = Image.FromFile(ofd1.FileName)
End If
End Sub
Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click
cmd = New SqlCommand("Insert into TBL_Image(Description, Image) values(#Description, #Image)", sqlcon)
cmd.Parameters.Add(New SqlParameter("#Description", SqlDbType.Text)).Value = txtDescription.Text
Dim ms1 As New MemoryStream
pbox1.Image.Save(ms1, pbox1.Image.RawFormat)
Dim Image() As Byte = ms1.ToArray
cmd.Parameters.Add(New SqlParameter("#Image", SqlDbType.Image)).Value = Image
sqlcon.Open()
cmd.ExecuteNonQuery()
sqlcon.Close()
MsgBox("Added successfully")
End Sub
Private Sub btnBrowse2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse2.Click
ofd2.Filter = "All Images |*.PNG; *.JPG; *.BMP; *.GIF; *.JPEG"
If ofd2.ShowDialog = DialogResult.OK Then
pbox2.Image = Image.FromFile(ofd2.FileName)
End If
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim msnew As New MemoryStream
pbox2.Image.Save(msnew, pbox2.Image.RawFormat)
Dim Image() As Byte = msnew.ToArray
selectImage(pbox2.Image)
End Sub
End Class

Using VB.Net to Insert Data to an Access Database

Does anyone have an idea on how to update the actual access datbase file? This is my code so far and I think everything is right, but when hit the button to send the information to the actual database file it does not appear in there. Can someone help me with this? The access file I'm talking about is the one outside of the visual basic project itself, but still connected.
Code
Imports System.Data.OleDb
Public Class Form1
Dim provider As String
Dim datafile As String
Dim connString As String
Dim con As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source=G:\Music Session Database\Music Database.accdb")
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
Me.Close()
End Sub
Private Sub btnsubmit_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnsubmit1.Click
Me.Music_DatabaseTableAdapter.Insert(Me.songTitle.Text, Me.songArtist.Text, Me.songAlbum.Text, Me.yearReleased.Text)
Me.Music_DatabaseTableAdapter.Fill(Me.Music_DatabaseDataSet.Music_Database)
con.Open()
MsgBox("Record Added")
con.Close()
songTitle.Text = ""
songArtist.Text = ""
songAlbum.Text = ""
yearReleased.Text = ""
End Sub
Private Sub btnsumbit2_Click(sender As Object, e As EventArgs) Handles btnsumbit2.Click
Me.Play_SessionTableAdapter.Insert(Me.songTitle.Text, Me.songArtist.Text, Me.songAlbum.Text, Me.yearReleased.Text, Me.datePlayed.Text, Me.timePlayed.Text, Me.genre.Text)
Me.Play_SessionTableAdapter.Fill(Me.Music_DatabaseDataSet.Play_Session)
con.Open()
MsgBox("Record Added")
con.Close()
songTitle.Text = ""
songArtist.Text = ""
songAlbum.Text = ""
yearReleased.Text = ""
datePlayed.Text = ""
timePlayed.Text = ""
genre.Text = ""
End Sub
Private Sub btnsubmit3_Click(sender As Object, e As EventArgs) Handles btnsubmit3.Click
Me.Song_Artist_InformationTableAdapter.Insert(Me.songArtist.Text, Me.genre.Text, Me.origin.Text, Me.artistInformation.Text)
Me.Song_Artist_InformationTableAdapter.Fill(Me.Music_DatabaseDataSet.Song_Artist_Information)
con.Open()
MsgBox("Record Added")
con.Close()
songArtist.Text = ""
genre.Text = ""
origin.Text = ""
artistInformation.Text = ""
End Sub
Private Sub btnclear_Click(sender As Object, e As EventArgs) Handles btnclear.Click
songTitle.Clear()
songArtist.Clear()
songAlbum.Clear()
yearReleased.Clear()
datePlayed.Clear()
timePlayed.Clear()
genre.Clear()
artistInformation.Clear()
End Sub
Private Sub FillByToolStripButton_Click(sender As Object, e As EventArgs)
Try
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Music_DatabaseBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles Music_DatabaseBindingNavigatorSaveItem.Click
Me.Validate()
Me.Music_DatabaseBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Music_DatabaseDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Song_Artist_Information' table. You can move, or remove it, as needed.
Me.Song_Artist_InformationTableAdapter.Fill(Me.Music_DatabaseDataSet.Song_Artist_Information)
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Play_Session' table. You can move, or remove it, as needed.
Me.Play_SessionTableAdapter.Fill(Me.Music_DatabaseDataSet.Play_Session)
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Music_Database' table. You can move, or remove it, as needed.
Me.Music_DatabaseTableAdapter.Fill(Me.Music_DatabaseDataSet.Music_Database)
End Sub
Private Sub btnupdate1_Click(sender As Object, e As EventArgs) Handles btnupdate1.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Music Database]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Music_DatabaseDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
Private Sub btnupdate2_Click(sender As Object, e As EventArgs) Handles btnupdate2.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Play Session]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Play_SessionDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
Private Sub btnupdate3_Click(sender As Object, e As EventArgs) Handles btnupdate3.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Song Artist Information]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Song_Artist_InformationDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
End Class
Format of the initialization string does not conform to specification
The connString you create is not valid.
provider = "Microsoft.ACE.OLEDB.12.0"
datafile = "H:\Music Session Database\Music Database.accdb"
connString = provider & datafile
Console.WriteLine(connString)
shows
Microsoft.ACE.OLEDB.12.0H:\Music Session Database\Music Database.accdb
What you want to do is something like
connString = String.Format("Provider={0};Data Source={1}", provider, datafile)
which produces
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Music Session Database\Music Database.accdb

Value cannot be NULL when saving DataGridView to SQL dB

I have a form with a datagridview (ViewCustomersForm) and a save button.
What I am trying to do is get the user to edit the infotmation in the datagrid view and then hit a save button, which will save the values back to my SQL table.
Unfortunately though, when my save button is pressed I get the following error.
"Value cannot be null."
Pointing at this line of code:
dataadapter.Update(ds.Tables("Customers_table"))
In the context of the below code:
Private Sub ViewCustomersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Customers._Customers' table. You can move, or remove it, as needed.
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim ds As DataSet = New DataSet()
'---open the connection and fill the dataset---
conn.Open()
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
End Sub
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim ds As DataSet = New DataSet()
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim sqlCmdBuilder As New SqlCommandBuilder(dataadapter)
sqlCmdBuilder.GetUpdateCommand()
dataadapter.Update(ds.Tables("Customers_table"))
End Sub
I am relatively new to VB, so any help or pointers greatly appreciated.
Thanks
I needed to have by variables defined at the Class level, not with in the Subs.
Here is the working code.
Imports System.Data.SqlClient
Imports System.Data.Common
Public Class ViewCustomersForm
Dim ds As DataSet = New DataSet()
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(Sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Private Sub Button1_Click(sender As Object, e As EventArgs)
End Sub
Private Sub ViewCustomersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'---open the connection and fill the dataset---
conn.Open()
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
End Sub
Private Sub Button_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlCmdBuilder As New SqlCommandBuilder(dataadapter)
sqlCmdBuilder.GetUpdateCommand()
dataadapter.Update(ds.Tables("Customers_table"))
End Sub
End Class

Database update will not work

I know that you guys will find this simple, but can anyone tell me why I am getting a syntax error despite following every instruction on numerous sites?
My code in full is:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = F:\Brett\Programming Projects\Roster\Roster.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
' This is grabbing all the records from the listing table in the Roster Database
sql = "Select * FROM Listing"
' Or selected columns
'sql = "SELECT Listing.FName, Listing.LName FROM Listing"
da = New OleDb.OleDbDataAdapter(sql, con)
' Populate the dataset with the data adaptor. This can be any name
da.Fill(ds, "Roster")
con.Close()
MaxRows = ds.Tables("Roster").Rows.Count
inc = -1
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim iRow As Integer = Me.Label1.Text
Dim junk As Integer
ds.Tables("Roster").Rows(iRow).Item(5) = Me.TextBox3.Text
ds.Tables("Roster").Rows(iRow).Item(6) = Me.TextBox4.Text
ds.Tables("Roster").Rows(iRow).Item(8) = Me.TextBox5.Text
da.Update(ds, "Roster")
'da.Update(ds)
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim newtbl As DataTable
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim cmd As New OleDb.OleDbCommand
newtbl = ds.Tables("Roster")
Dim drCurrent As DataRow
drCurrent = newtbl.NewRow()
drCurrent(1) = "sfd"
drCurrent(2) = "werter"
newtbl.Rows.Add(drCurrent)
da.Update(ds, "Roster")
End Sub
No matter what I do, I get this error message. Any help will be greatly appreciated as this is two days now...
I would show you my error but as usual, some peanut won't let me without some crap.. It states OleDbException was unhandled, Syntax error in Insert Into statement.
Can you try wrapping your database calls in a try-catch block and inspect the InnerXml that's returned with the exception?
That might give you more information about the error that you're getting.

Resources