Error: No data exists for the row/column - vb.net

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()

Related

How to check if byte is null vb.net

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

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

Load SQL Statement for Dataset From SqlServer

I have a code that will fill the dataset for my crystal report which was written down as follows:
Dim str1 As String = "SELECT * FROM farm_loan WHERE id = '" & txtAgreement.Text & "'"
Dim str2 As String = "SELECT * FROM cd_farmers WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str3 As String = "SELECT * FROM cd_Address WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str4 As String = "SELECT * FROM cd_loan_charges WHERE loanid = '" & txtAgreement.Text & "'"
Dim ad1 As SqlDataAdapter = New SqlDataAdapter(str1, Conn)
Dim ad2 As SqlDataAdapter = New SqlDataAdapter(str2, Conn)
Dim ad3 As SqlDataAdapter = New SqlDataAdapter(str3, Conn)
Dim ad4 As SqlDataAdapter = New SqlDataAdapter(str4, Conn)
Dim LDPSDataSet As DataSet = New DataSet()
ad1.Fill(LDPSDataSet, "farm_loan")
ad2.Fill(LDPSDataSet, "cd_farmers")
ad3.Fill(LDPSDataSet, "cd_Address")
ad4.Fill(LDPSDataSet, "cd_loan_charges")
The above code works fine. What I am trying to do is to store the sql statement in one table called tblDataSet and load the same from sql server. Here are my code.
cmd = New SqlCommand("SELECT * FROM tblDataSet WHERE Flag = 'Y'", Conn)
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim ad As SqlDataAdapter
If reader.HasRows Then
Do While reader.Read()
MySql = reader(1).ToString
Dim table As String = reader(2).ToString
Dim comm As SqlCommand = New SqlCommand(MySql)
comm.Connection = Conn
comm.CommandType = CommandType.Text
comm.Parameters.Add("#AgreementID", SqlDbType.Int).Value=txtAgreement.Text
comm.Parameters.Add("#CustomerID", SqlDbType.Int).Value = txtCustID.Text
Dim ad As SqlDataAdapter = New SqlDataAdapter
For Each tbl As DataTable In LDPSDataSet.Tables()
If tbl.TableName = table Then
ad.SelectCommand = comm
End If
Exit For
ad.Update(tbl)
Next
Loop
End If
I have not encountered any error but no value is fetch to the crystal report.
My code in to fetch data to crystal report is show below.
With mReport
repOptions = .PrintOptions
With repOptions
.PaperOrientation = rptOrientation
.PaperSize = rptSize
.PrinterName = printer
End With
.Load(rptPath, OpenReportMethod.OpenReportByDefault)
.SetDataSource(LDPSDataSet)
'.Refresh()
.PrintToPrinter(1, True, 0, 0)
End With
Please help me identify the problem with my code.
Thanks in advance.

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