Populate Combobox from SQL Server vb.net - sql-server

I'm trying to populate a combobox with data from SQL Server. This is my code so far. There are asterisks around the errors. Also, ignore the comments.
Private Sub frmOriginal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connetionString As String = Nothing
Dim sqlcon As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
connetionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
sql = "select * from TickerSymbol"
sqlcon = New SqlConnection(connetionString)
Try
sqlcon.Open()
command = New SqlCommand(sql, sqlcon)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
sqlcon.Close()
cboID.DataSource = ds.Tables(0)
cboID.ValueMember = "TickerSymbol"
cboID.DisplayMember = "TickerSymbol"
Catch ex As Exception
'MessageBox.Show("Can not open connection ! ")'
End Try
End Sub
Private Sub cboID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboID.SelectedIndexChanged
Dim dr As SqlDataReader
Dim command As New SqlCommand *(queryString, connection)*
Dim dataReader As SqlDataReader = command.ExecuteReader()
Dim sqlcon As SqlConnection
Dim cmd As SqlCommand
sqlcon = New SqlConnection
sqlcon.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
Try
sqlcon.Open()
cmd = New SqlCommand
cmd.CommandText = " select * from TickerSymbol where TickerSymbol = '" & cboID.Text & "'"
cmd = New SqlCommand(cmd.CommandText, sqlcon)
dr = cmd.ExecuteReader
While dr.Read()
'TxtID.Text = dr.GetInt32(0)'
'TxtSN.Text = dr.GetString(1)'
'TxtGender.Text = dr.GetString(2)'
'TxtPhone.Text = dr.GetInt32(3)'
'TxtAdrress.Text = dr.GetString(4)'
lblCompanyName.Text = dataReader.GetString(1)
lblPurchasePrice.Text = dataReader.GetSqlMoney(2)
lblQtyPurchased.Text = dataReader.GetInt32(3)
lblPurchaseDate.Text = dataReader.GetDateTime(4)
End While
sqlcon.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
sqlcon.Dispose()
End Sub

Please use parameterized queries as this will format values properly e.g. apostrophes in text will escape properly with parameters while without you must handle them, dates will be formatted properly too. Code is much cleaner also.
Example, syntax for Framework 3.5 and higher. If a connection string is used more than once then consider placing it in a private variable or under My.Settings under project properties.
Using cn As New SqlConnection With {.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"}
Using cmd As New SqlCommand With {.Connection = cn, .CommandText = "select * from TickerSymbol where TickerSymbol = #TickerSymbol"}
cmd.Parameters.AddWithValue("#TickerSymbol", cboID.Text)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
'
'
'
End While
End If
End Using
End Using

Related

"System.OutOfMemoryException: 'Out of memory.'" when reading image from SQL Server

I have images assigned to every button in my VB.NET form, the images come from SQL Server. The data type is varbinary(MAX).
This is my code:
Using con As New SqlConnection("con string")
Dim sql As String = "SELECT * FROM Inventory WHERE ID=#ID"
Using cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = 3
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
If myreader.Read() AndAlso Not DBNull.Value.Equals(myreader("Image")) Then
Boton3.Text = myreader("Item")
Boton3.Enabled = myreader("ONOFF")
Dim ImgSql() As Byte = DirectCast(myreader("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton3.BackgroundImage = Image.FromStream(ms)
con.Close()
End Using
Else
Boton3.Text = myreader("Item")
Boton3.BackgroundImage = Nothing
Boton3.Enabled = myreader("ONOFF")
End If
End Using
End Using
End Using
The platform is 64bit. I'm thinking it might have to do with not disposing properly, but I'm not sure since I'm new to coding.
EDIT SHOWING NEW CODE AND HOW I RETRIVE MORE THAN ONE RECORD:
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Dim dt As DataTable
Try
dt = GetInventoryDataByID(1)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt.Rows.Count > 0 Then
Boton1.Text = dt.Rows(0)("Articulo").ToString
Boton1.Enabled = CBool(dt.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt.Rows(0)("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton1.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton1.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
Dim dt2 As DataTable
Try
dt2 = GetInventoryDataByID(2)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt2.Rows.Count > 0 Then
Boton2.Text = dt2.Rows(0)("Articulo").ToString
Boton2.Enabled = CBool(dt2.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt2.Rows(0)("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(dt2.Rows(0)("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton2.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton2.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
End Sub
Private Function GetInventoryDataByID(id As Integer) As DataTable
Dim dt As New DataTable
Dim sql As String = "SELECT Imagen, Articulo, ONOFF FROM Inventario WHERE ID=#ID"
Using con As New SqlConnection("CON STRING"),
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = id
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
dt.Load(myreader)
End Using
End Using
Return dt
End Function
End Class
You don't want to hold a connection open while you update the user interface. Separate you user interface code from your database code.
If you put a comma at the end of the first line of the outer Using block, both the command and the connection are included in same block. Saves a bit of indenting.
You are passing an integer to the #ID parameter but you have set the SqlDbType as a VarChar. Looks like a problem. I changed the SqlDbType to Int.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As DataTable
Try
dt = GetInventoryDataByID(3)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt.Rows.Count > 0 Then
Boton3.Text = dt.Rows(0)("Item").ToString
Boton3.Enabled = CBool(dt.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt.Rows(0)("Image")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton3.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton3.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
End Sub
Private Function GetInventoryDataByID(id As Integer) As DataTable
Dim dt As New DataTable
Dim sql As String = "SELECT * FROM Inventory WHERE ID=#ID"
Using con As New SqlConnection("con string"),
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = id
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
dt.Load(myreader)
End Using
End Using
Return dt
End Function
EDIT Add Dispose on image
If Not DBNull.Value.Equals(dt.Rows(0)("Image")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
If Boton3.BackgroundImage IsNot Nothing Then
Boton3.BackgroundImage.Dispose()
End If
Boton3.BackgroundImage = Image.FromStream(ms)
End Using
Else
If Boton3.BackgroundImage IsNot Nothing Then
Boton3.BackgroundImage.Dispose()
End If
End If
I resolved this issue by simply not using buttons. Instead I used pictureboxes as buttons and that resolved the issue. Im guesssing the problem is that buttons don't allow as much memory as pictureboxes.

Error: Fill: selectcommand.connection property has not been

I'm trying to retrieve binary data from a database.
I got this error: "Error: Fill: selectcommand.connection property has not been". I can't locate the error.
Public Shared Function BinaryData(ByVal sFileName As String) As Byte()
Dim strSql As String
Dim binaryFile As Byte() = Nothing
Dim dt As DataTable
Dim myCommand As New SqlCommand
Dim sqlConn As New SqlConnection
sqlConn = New SqlConnection("Data Source=xxx;Initial Catalog=xx;Persist Security Info=True;User ID=wxx;Password=xx;MultipleActiveResultSets=True;Application Name=EntityFramework")
sqlConn.Open()
myCommand.Connection = sqlConn
strSql = "SELECT Data FROM tbldrive WHERE Filename = '" + sFileName + "'"
Dim scmd As New SqlCommand(strSql, sqlConn)
dt = DataComponent.DataTableQuery(DataComponent.SqlConn, strSql)
If dt.Rows.Count > 0 Then
Try
binaryFile = DirectCast(dt.Rows(0).Item("Data"), Byte())
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Return binaryFile
End Function
It looks like you've tried a few things in that code but accidentally left the remains of some attempts in there.
There are some things you could do a bit differently: as you're only after one item from the database, you can use ExecuteScalar; and when the code has finished with the SQL connection and command, they should have .Dispose() called on them - the Using statement will take care of that for you even if something goes wrong. Finally, you should always use SQL parameters to pass parameters to an SQL query - it makes it more secure and avoids having to worry about things like apostrophes in the value.
Public Shared Function BinaryData(ByVal sFileName As String) As Byte()
Dim sql As String = "SELECT Data FROM tbldrive WHERE Filename = #fname"
Dim connStr = "Data Source=xxx;Initial Catalog=xx;Persist Security Info=True;User ID=wxx;Password=xx;MultipleActiveResultSets=True;Application Name=EntityFramework"
Dim binaryFile As Byte() = Nothing
Using conn As New SqlConnection(connStr),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {
.ParameterName = "#fname",
.SqlDbType = SqlDbType.NVarChar,
.Size = 255,
.Value = sFileName})
conn.Open()
Dim obj As Object = cmd.ExecuteScalar()
If obj IsNot Nothing Then
Try
binaryFile = DirectCast(obj, Byte())
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Using
Return binaryFile
End Function
(You may need to adjust the .SqlDbType and .Size parameters: they need to match the column type and size in the database. Also, you probably don't need MultipleActiveResultSets.)
The problem seems to be that you have two SqlCommand objects:
Dim myCommand As New SqlCommand
...
myCommand.Connection = sqlConn
It's assigned but not used.
Then you have defined another one:
Dim scmd As New SqlCommand(strSql, sqlConn)
that is not used either.
And I don't know why you have this:
dt = DataComponent.DataTableQuery(DataComponent.SqlConn, strSql)
Do you even need a SqlCommand if you are not using it ?
Clean up your code by removing unused variables.

Error database is locked sqlite vb.net

hi I'm trying to insert a row to my database but I still get this error message (see below):
I used the methode using to be sure that the connection will be closed.
below the script for the insert button :
Private Sub MTB_Insert_Click(sender As Object, e As EventArgs) Handles MTB_Insert.Click
cmd = New SQLite.SQLiteCommand
Using con As New SQLite.SQLiteConnection(constr)
Try
'con.ConnectionString = constr
con.Open()
cmd.Connection = con
cmd.CommandText = "Insert Into Material_Type (Material_Type,Material_Type_Description) values(#Type,#Description)"
cmd.Parameters.AddWithValue("#Type", MTTB_Material_Type.Text)
cmd.Parameters.AddWithValue("#Description", MTTB_Material_Description.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Successful Added Data")
'Calling function load data
loadDatadg1()
'con.Dispose()
'con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
other parts of my code :
Public Class F_Update
Dim con As SQLite.SQLiteConnection
Dim cmd As SQLite.SQLiteCommand
Dim da As SQLite.SQLiteDataAdapter
Dim constr As String = "Data source =Database1.db"
Public Sub loadDatadg1()
Using con As New SQLite.SQLiteConnection(constr)
'con = New SQLite.SQLiteConnection(constr)
con.Open()
Dim str As String = "select * from Material_type"
da = New SQLite.SQLiteDataAdapter(str, con)
Dim ds As New DataSet
da.Fill(ds, "Tb.Material_Type")
dg1.DataSource = ds.Tables("Tb.Material_Type")
'da.Dispose()
'con.Close()
End Using
End Sub
Private Sub F_Update_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using con As New SQLite.SQLiteConnection(constr)
' con = New SQLite.SQLiteConnection(constr)
con.Open()
'MsgBox("OK")
'Calling the function Load form
loadDatadg1()
End Using
End Sub
another part :
Private Sub B_login_Click(sender As Object, e As EventArgs) Handles B_login.Click
Dim connectionString As String = "Data source =Database1.db"
Dim mSQL As String = "select User_Name,User_Password from User where (User_ID = 1 and User_Name = '" & T_User_Name.Text & "' and User_Password = '" & T_User_Password.Text & "')"
Dim dt As DataTable = Nothing
Dim ds As DataSet
Dim rd As SQLiteDataReader
Using con As New SQLiteConnection(connectionString)
Try
con.Open()
Dim cmd As New SQLiteCommand(mSQL, con)
cmd.ExecuteNonQuery()
rd = cmd.ExecuteReader
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If rd.HasRows Then
F_Update.Show()
Me.Close()
Else
MessageBox.Show("Invalid User Name or Password")
End If
'con.Close()
End Using
End Sub
End Class
can some one help me please ? Thanks in advance

getting Count(Record) result to a variable in VB.Net

I want to capture count of record to a variable but code is not working. Please assist
Dim PrevRgAPAC As Integer
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
con.ConnectionString = "Data Source=XXXXXXXXXXX; initial catalog=XXXXXXXXXXXX; Integrated Security=true"
cmd.Connection = con
con.Open()
cmd.CommandText = "select count(record) from tblKPI where user_region='APAC' AND payroll_month='February'"
rd = cmd.ExecuteReader
If rd.HasRows Then
rd.Read()
PrevRgAPAC = rd.Item("exec")
Else
MsgBox("Not Found")
End If
Thank you
Try to use SqlCommand.ExecuteScalar Method:
PrevRgAPAC = Convert.ToInt32(cmd.ExecuteScalar())
Assuming that PrevRgAPAC is the variable in which you want to store the value of count. So your code would look like this:
Dim PrevRgAPAC As Int32 = 0
Dim sql As String = "select count(record) from tblKPI where user_region='APAC' AND payroll_month='February'"
Using conn As New SqlConnection("Data Source=XXXXXXXXXXX; initial catalog=XXXXXXXXXXXX; Integrated Security=true")
Dim cmd As New SqlCommand(sql, conn)
Try
conn.Open()
PrevRgAPAC = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using

Displaying data from a dataset vb.net

I am having issues returning data from a MS SQL database.
The code is returning 'System.data.datarowview' instead of the results of my query. The code for the sub is:
Public Sub newquery(query As String)
Dim SQLConn As SqlConnection = New SqlConnection
Dim SqlCommand As New SqlCommand
SQLConn.ConnectionString = "Data Source=.\testing;Initial Catalog=eurostyle;Integrated Security=SSPI;"
SqlCommand = New SqlCommand(query, SQLConn)
Try
SQLConn.Open()
sqlDA = New SqlDataAdapter(SqlCommand)
sqlDataset = New DataSet
sqlDA.Fill(sqlDataset)
SQLConn.Close()
listbox1.DataContext = sqlDataset
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I am new to WPF and I'm sure that is only something trivial.
Any help is greatly appreciated!
DataGrid view would be more appropriate to display results from database.
Try this:
Public Sub newquery(query As String)
Dim SQLConn As SqlConnection = New SqlConnection
Dim SqlComm As New SqlCommand
Dim dbDataSet As New DataTable
Dim bSource As New BindingSource
Dim sqlDA As New SqlDataAdapter
SQLConn.ConnectionString = "Data Source=.\testing;Initial Catalog=eurostyle;Integrated Security=SSPI;"
Try
SQLConn.Open()
SqlComm = SQLConn.CreateCommand
SqlComm.CommandText = query
SqlComm = New SqlCommand(zapytanie, myConn)
sqlDA.SelectCommand = SqlComm
sqlDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView.DataSource = bSource
sqlDA.Update(dbDataSet)
SQLConn.Close()
Catch ex As SqlException
MessageBox.Show("Query Error: " & ex.Message)
End Try

Resources