How to check if byte is null vb.net - sql

I'm assigning background images to every button according to my SQL Server database. If a byte is null I get this error:
Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
I want to allow buttons with no background images, but the error is preventing me.
Here is what I attempted:
Dim strsql As String
Dim ImgSql() As Byte
Using con As New SqlConnection("constring")
con.Open()
strsql = "SELECT Imagen FROM Inventario WHERE ID=#ID"
Dim cmd As New SqlCommand(strsql, con)
ItemID = 1
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ItemID
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
ImgSql = myreader("Imagen")
If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then
Dim ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
con.Close()
Else
'do nothing
End If
End Using

Dim ItemID As Integer = 1
Dim sql As String = "SELECT Imagen FROM Inventario WHERE ID=#ID"
Using con As New SqlConnection("constring"), _
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Integer).Value = ItemID
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
If myreader.Read() AndAlso Not DBNull.Value.Equals(myreader("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(myreader("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
End Using
End If
End Using
End Using

Based on this answer in C#, converted to vb.net and added NULL check
Using con As New SqlConnection("constring")
Using cmd = con.CreateCommand()
cmd.CommandText = "SELECT Imagen FROM Inventario WHERE ID=#ID"
Dim ItemID = 1
cmd.Parameters.AddWithValue("#ID", ItemID)
con.Open()
Dim res = cmd.ExecuteScalar()
If res IsNot Nothing Then
ImgSql = CType(res, Byte())
If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then
Dim ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
End If
End If
End Using
End Using

Related

How can I insert an image from SQL Server onto a button in VB.net?

I am having issues assigning an image to every button according to my database.
My current code:
Dim strsql As String
Dim ImgSQl As Image
Dim con As New SqlConnection("constring")
con.Open()
strsql = "SELECT Image FROM Inventory WHERE ID=#ID"
Dim cmd As New SqlCommand(strsql, con)
ItemID = 1
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ItemID
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
ImgSQl = myreader("Image")
con.Close()
btn1.Image = ImgSQl
This is the error I'm getting:
Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'
All I had to do was dim as Byte, also adding "()" is really important for it to work. Hope answering my own question helps a VB.net beginner out there.
Dim strsql As String
Dim ImgSql() As Byte
Using con As New SqlConnection("constring")
con.Open()
strsql = "SELECT Image FROM Inventory WHERE ID=#ID"
Dim cmd As New SqlCommand(strsql, con)
ItemID = 1
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ItemID
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
ImgSql = myreader("Imagen")
Dim ms As New MemoryStream(ImgSql)
btn1.Image = Image.FromStream(ms)
con.Close()
End Using

how to use date in where clause to search data from access data base in vb.net?

i want to search data from my data base using date in where clause.
But i am getting an error while executing the code.
I am trying this code.
Sub comboboxSELECTED()
Dim a As Date
Form1.ComboBox1.Text = a
Dim con As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Mdm.accdb"
con.Open()
Dim q As String = "select * from Rice Where DateReceived =" & Form1.ComboBox1.SelectedText
Dim cmd As New OleDb.OleDbCommand(q, con)
Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
While Reader.Read
Form1.ListView1.Items.Add(Reader(0))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(1))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(2))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(3))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(4))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(5))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(6))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(7))
Form1.DateTimePicker1.Text = Reader("DateReceived")
Form1.TxtEnrolment.Text = Reader("Enrolment")
Form1.TxtReceived.Text = Reader("QtyReceived")
Form1.TxtTotal.Text = Reader("TotalQuantity")
Form1.TxtUtilised.Text = Reader("QtyUtilised")
Form1.TxtBalance.Text = Reader("Balance")
End While
Reader.Close()
con.Close()
End Sub
Please try changing that section of code to this:
String q = "select * from Rice Where DateReceived = #datercvd";
OleDb.OleDbCommand cmd = New OleDb.OleDbCommand(q, con);
OleDbParameter objectdate = new OleDbParameter("#datercvd", OleDbType.DBDate);
objectdate.Value = Convert.ToDateTime(Form1.ComboBox1.SelectedText);
cmd.Parameters.Add(objectdate);
It does a match on the date, converts from a string, and takes care of SQL injection isues.
The VB.net code...
Private Sub ComboBoxSelected()
Using con As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Mdm.accdb"
Dim q As String = "Select * from Rice Where DateReceived =#DateReceived"
Using cmd As New OleDb.OleDbCommand(q, con)
cmd.Parameters.Add("#DateReceived", OleDbType.Date).Value = CDate(Form1.ComboBox1.SelectedText)
con.Open()
Using Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
While Reader.Read
'Your code
End While
End Using
End Using
End Using
End Sub

Sending updates from datagridview to existing row in database

I am retrieving records from a database with the following code.
Dim SearchID As Integer = teacherID
Dim NewStudentID As Integer = studentID
Dim DisplayTable As New DataTable()
Dim da As New OleDbDataAdapter()
Dim sqlquery As String = ("select * from tblAppointments WHERE TeacherID =" & teacherID & "")
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
da.SelectCommand = New OleDbCommand(sqlquery, conn)
da.Fill(Finalds, "Display")
DisplayTable = Finalds.Tables("Display")
DisplayTable.Columns.Remove("Instrument")
DisplayTable.Columns.Remove("Room")
DisplayTable.Columns.Remove("TeacherID")
Registersgridview.DataSource = DisplayTable
Registersgridview.Columns(0).Visible = False
conn.Close()
Catch ex As Exception
MsgBox("There are no appointments in the database for " + Tutorcombox.Text)
End Try
It also there then added to a datagridview and certain columns are removed and some are hidden aswell.
Because its essentially a register, when the use clicks on the datagridview field that is a boolean it changes from false to true. I have been trying to send this back to the database, but have had no luck. I have tried the following :
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next
But have had no luck with doing so, as it crashes without an error.
Can anyone help?
I solved the problem myself, if any of you are having similar problems here is the solution
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
Dim appID As Integer = Registersgridview.Rows(i).Cells(0).Value
Dim present As Boolean = Registersgridview.Rows(i).Cells(4).Value
row = dt.Rows.Add
row.Item("appID") = appID
row.Item("Present") = present
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "UPDATE tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.Connection = conn
.ExecuteNonQuery()
End With
Next
conn.Close()
Registersgridview.DataSource = Nothing
dt.Clear()
try this:
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(5))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next

Error: No data exists for the row/column

I get the following error: No data exists for the row/column.
It should retrieve the image
sSql = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC"
Dim cmd As New OleDbCommand(sSql, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
dr.Read()
lab1id.Text = dr.GetValue(1).ToString
lab1fname.Text = dr.GetValue(2).ToString
lab1lname.Text = dr.GetValue(3).ToString
lab1position.Text = dr.GetValue(4).ToString
lab1subject.Text = dr.GetValue(5).ToString
dr.Close()
sSql = "select Pfile from Faculty where StId = '" & lab1id.Text & "'"
Dim pcmd As New OleDbCommand(sSql, con)
Dim pdr As OleDbDataReader = cmd.ExecuteReader()
pdr.Read()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
pdr.Close()
The dr.GetValue(N) is zero-based ordinal. Change your indices:
While dr.Read()
lab1id.Text = dr.GetValue(0).ToString
lab1fname.Text = dr.GetValue(1).ToString
lab1lname.Text = dr.GetValue(2).ToString
lab1position.Text = dr.GetValue(3).ToString
lab1subject.Text = dr.GetValue(4).ToString
End While
While pdr.Read() ' | you got a typo here. Change `dr` to `pdr`.
Dim bits As Byte() = CType(pdr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
End While
Consider changing your code to something like this:
Using command As OleDbCommand = con.CreateCommand()
command.CommandText = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC;"
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
lab1id.Text = reader.Item("id").ToString
lab1fname.Text = reader.Item("fname").ToString
lab1lname.Text = reader.Item("lname").ToString
lab1position.Text = reader.Item("position").ToString
lab1subject.Text = reader.Item("subject").ToString
End While
End Using
End Using
Using command As OleDbCommand = con.CreateCommand()
command.CommandText = "select Pfile from Faculty where StId = #StId;"
command.Parameters.AddWithValue("#StId", lab1id.Text)
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
Dim bits As Byte() = CType(reader.Item("Pfile"), Byte())
Using stream As New MemoryStream(bits)
imgRetrieve.Image = Bitmap.FromStream(stream)
End Using
End While
End Using
End Using
The problem is you never execute pcmd, see the following two lines:
Dim pcmd As New OleDbCommand(sSql, con)
Dim pdr As OleDbDataReader = cmd.ExecuteReader() ' cmd should be replaced with pcmd
I would suggest adding While...End While Statement when getting the values from dr and pdr. You also need to parameterize the second query to avoid SQL Injection.
sSql = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC"
Dim cmd As New OleDbCommand(sSql, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
lab1id.Text = dr.GetValue(1).ToString
lab1fname.Text = dr.GetValue(2).ToString
lab1lname.Text = dr.GetValue(3).ToString
lab1position.Text = dr.GetValue(4).ToString
lab1subject.Text = dr.GetValue(5).ToString
End While
dr.Close()
sSql = "select Pfile from Faculty where StId = #StId"
Dim pcmd As New OleDbCommand(sSql, con)
pcmd.Parameters.AddWithValue("#StId", lab1id.Text)
Dim pdr As OleDbDataReader = pcmd.ExecuteReader()
While pdr.Read()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
End While
pdr.Close()

Using SQLDataReader instead of recordset

I am new to this and had this question. Can I use SQLDataReader instead of a Recordset. I want to achieve the following result in an SQLDataReader.
Dim dbConn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sqlstr As String = "SELECT Name,Status FROM table1 WHERE id=" + item_id.Value.ToString
rs.Open(SQL, dbConn)
While Not rs.EOF
txtName.Text = rs.Fields.Item("Name").Value
ddlstatus.SelectedIndex = 1
rs.MoveNext()
End While
rs.Close()
rs = Nothing
dbConn.Close()
dbConn = Nothing
Can I replace recordset with SQLDataReader and if I can can you please show me the changes in code?
Its highly recommend that you use the using pattern:
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New SqlConnection(sConnection)
Con.Open()
Using Com As New SqlCommand("Select * From tablename", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txtName.Text = RDR.Item("Name").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
You will have to swap out a few things, something similar to the following.
Here is an example, you will need to modify this to meet your goal, but this shows the difference.
I also recommend using a "Using" statement to manage the connection/reader. Also, a parameterized query.
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Dim objCommand As New SqlCommand
objCommand.CommandText = "Select * From tablename"
objCommand.Connection = New SqlConnection(sConnection)
objCommand.Connection.Open()
Dim objDataReader As SqlDataReader = objCommand.ExecuteReader()
If objDataReader.HasRows Then
Do While objDataReader.Read()
Console.WriteLine(" Your name is: " & Convert.ToString(objDataReader(0)))
Loop
Else
Console.WriteLine("No rows returned.")
End If
objDataReader.Close()
objCommand.Dispose()
Dim rdrDataReader As SqlClient.SqlDataReader
Dim cmdCommand As SqlClient.SqlCommand
Dim dtsData As New DataSet
Dim dtbTable As New DataTable
Dim i As Integer
Dim SQLStatement as String
msqlConnection.Open()
cmdCommand = New SqlClient.SqlCommand(SQLStatement, msqlConnection)
rdrDataReader = cmdCommand.ExecuteReader()
For i = 0 To (rdrDataReader.FieldCount - 1)
dtbTable.Columns.Add(rdrDataReader.GetName(i), rdrDataReader.GetFieldType(i))
Next
dtbTable.BeginLoadData()
Dim values(rdrDataReader.FieldCount - 1) As Object
While rdrDataReader.Read
rdrDataReader.GetValues(values)
dtbTable.LoadDataRow(values, True)
End While
dtbTable.EndLoadData()
dtsData.Tables.Add(dtbTable)
msqlConnection.Close()
Return dtsData