How to catch oledbdatareader errors - vb.net

I have this code i wrote to find out if a record exists in data base. It works well when record is found. If it isn't, it brings up an error. I would like the error to be caught in a messagebox that states "record not found" instead.
Dim findprinc As String = TextBox1.Text.Substring(0, 16)
MsgBox(findprinc)
sql = "Select RealID from Dets where ID like '%" & findprinc & "%'"
MsgBox(sql)
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\new.mdb")
conn.Open()
Dim cmd As New OleDbCommand(sql, conn)
Dim numeri As OleDbDataReader = cmd.ExecuteReader
numeri.Read()

Dim findprinc As String = TextBox1.Text.Substring(0, 16)
MsgBox(findprinc)
Sql = "Select RealID from Dets where ID like '%" & findprinc & "%'"
MsgBox(Sql)
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\new.mdb")
conn.Open()
Dim cmd As New OleDbCommand(Sql, conn)
Dim numeri As OleDbDataReader = cmd.ExecuteReader
Dim recordFound As Boolean = False
While numeri.Read
recordFound = True
End While
If recordFound = False Then
MsgBox("Record Not Found")
End If

Related

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll No value given for one or more required parameters

So I'm trying to read a data row (of school subjects) from a MS Access file and add new ToolStripMenuItems during runtime named according to the data row items. This is my code:
dataFile = "C:\Users\Abenati Mawisa\Documents\Database1.mdb"
connString = provider & dataFile
myConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" & dataFile
myConnection.Open()
Dim str As String = "SELECT * FROM Gr8Subjects WHERE ID_PassportNum = ?"
Dim subjects(8) As String
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("ID_PassportNum", myuserName)
dr = cmd.ExecuteReader 'The error in the title is generated here
While dr.Read()
For k = 0 To 8
subjects(k) = dr("Subject" & k + 1).ToString
Next
End While
myConnection.Close()
SubjectsToolStripMenuItem.DropDownItems.Clear()
For l = 0 To 8
SubjectsToolStripMenuItem.DropDownItems.Add(subjects(l))
Next
myuserName is declared publicly and come from a different form. The code has run before without the error.
Before this part of my code,
Dim str As String = "SELECT * FROM Gr8Subjects WHERE ID_PassportNum = ?"
Dim subjects(8) As String
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("ID_PassportNum", myuserName)
dr = cmd.ExecuteReader
looked like this,
Dim str As String = "SELECT * FROM Gr8Subjects WHERE (ID_PassportNum = '" & myuserName & "')"
Dim subjects(8) As String
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
I changed it after a bit of research, but it still doesn't work.
Any help would be appreciated.

SQL select statement with 2 conditions

I have a table that has columns CustomerCell and ReceiptType. I need to create a SELECT statement that displays every record that matches CustomerCell or ReceiptType.
I tried this code:
If TextBox1.Text.Trim.Length <> 0 OrElse CheckBox4.Checked = True Then
Dim Conn As New SqlConnection(constr)
Dim ds As New DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt] where (RcptCustCell = '" & TextBox1.Text & "') or ([RcptType] = 'Cash') "
Dim da As New SqlDataAdapter(sqlstr, Conn)
ds.Reset()
da = New SqlDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Call griddraw()
Conn.Close()
End If
Where Textbox1 is for CustomerCell and CheckBox4 is for ReceiptType. When I enter customer cell and receipt type I should see 2 records however with the above code I can see only one record.
This is my form:
As stated, look into parameters to avoid SQL injection and it does clear up your query a little more. I've put this together which may help. Might need a few tweaks for your application:
If TextBox1.Text.Trim.Length <> 0 OrElse CheckBox4.Checked = True Then
Dim dt As DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt] where (RcptCustCell = #RcptCustCell) or ([RcptType] = 'Cash') "
Using con As New SqlConnection(constr),
com As New SqlCommand(sqlstr, con)
com.Parameters.Add("#RcptCustCell", SqlDbType.VarChar).Value = TextBox1.Text
con.Open()
dt = New DataTable
dt.Load(com.ExecuteReader)
dgv.DataSource = dt
Call griddraw()
End Using
End If
Dim Conn As New SqlConnection(constr)
Dim ds As New DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt]"
If TextBox1.Text.trim.length <> 0 then
sqlstr += "where (RcptCustCell = '" & TextBox1.Text & "')"
endif
If chkPaymentCheck.checked then
if sqlstr.contains("where") = false then
sqlstr += "where RcptType = 'Check'"
EndIf
sqlstr += "or RcptType = 'Check'"
endif
Dim da As New SqlDataAdapter(sqlstr, Conn)
ds.Reset()
da = New SqlDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Call griddraw()
Conn.Close()
Try this and you can continue with the if statements to add more checks.

VB.Net - ExecuteReader: CommandText property has not been initialized

I know there are some threads about this topic, but for some reason nothing of these things given there didn't work for me. So that is my code:
Dim strAccSQL As String = "SELECT nUserNo FROM dbo.tUser WHERE sUserID='" & AccountID.Text & "';"
Dim catCMDAcc As SqlCommand = New SqlCommand(strAccSQL, AccCon)
Dim myAccountReader As SqlDataReader = catCMDAcc.ExecuteReader()
While myAccountReader.Read
AccountNo.Text = myAccountReader(0)
End While
myAccountReader.Close()
Con.Close()
Con.Open()
Dim strSQL2 As String
Dim catCMD As SqlCommand = New SqlCommand(strSQL2, Con)
Dim myReader As SqlDataReader = catCMD.ExecuteReader()
InfoTextBox.Text &= Environment.NewLine & Now & " Account: " & AccountID.Text & " Found"
CharacterName.Properties.Items.Clear()
While myReader.Read()
CharacterName.Properties.Items.Add(myReader(0))
End While
myReader.Close()
AccCon.Close()
Con.Close()
Anyone got an idea for my problem?
As the errormessage states, your CommandText is empty string here (strSQL2):
Dim strSQL2 As String
Dim catCMD As SqlCommand = New SqlCommand(strSQL2, Con)
Dim myReader As SqlDataReader = catCMD.ExecuteReader()
You cannot execute an empty sql-clause.

Populating Datagrid

I am creating a pageant scoring system,
I have this functions for populating my datagridview's first column using query:
Public Sub searchContestant()
If comboCategory.SelectedIndex <> 0 Then
Dim id As Integer = Login.JudgeBindingSource1.Current("Cont_id")
Dim critID As Integer = Convert.ToInt32(lblID.Text)
'search the contest record by the contest_id
Dim con As New SqlConnection
Dim reader As SqlDataReader
Dim reader2 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
Try
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & critID & "' ", con)
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
' Execute Query
reader = cmd.ExecuteReader()
nc.Name = "Contestants"
nc.Width = 250
nc.ReadOnly = True
DataGridView1.Columns.Add(nc)
While reader.Read()
nc = New DataGridViewTextBoxColumn
nc.Name = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.HeaderText = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.Width = 150
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
Try
'populate contestant rows
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
reader2 = cmd2.ExecuteReader()
While reader2.Read()
nc = New DataGridViewTextBoxColumn
nc.Width = 100
DataGridView1.Rows.Add(reader2.GetString(2).ToString())
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End If
End Sub
And for succeeding columns :
Public Sub searchCriteria()
Dim con As New SqlConnection
Dim reader4 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
Try
'populate Criteria
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & lblID.Text & "' ", con)
con.Open()
reader4 = cmd.ExecuteReader
While reader4.Read
nc = New DataGridViewTextBoxColumn
nc.Name = reader4.GetString(1).ToString & Chr(13) & reader4.GetString(2).ToString & "%"
nc.Width = 100
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End Sub
This is the output:
And everytime a judge login, I insert data into the system with this function:
Public Sub makeTransaction()
Dim con2 As New SqlConnection
'get the judge id upon logging in
Dim judgeID = Login.JudgeBindingSource1.Current("Judge_id")
'get the contest id of the judge
Me.JudgeTableAdapter.FillByJudgeID(Me.PSSDataSet.Judge, judgeID)
Dim JudgeContestid = Login.JudgeBindingSource1.Current("Cont_id")
Me.ContestantTableAdapter.FillByContestID(Me.PSSDataSet.Contestant, JudgeContestid)
'get the contestant id
Me.ContestTableAdapter.FillByContestID(Me.PSSDataSet.Contest, JudgeContestid)
Dim contestID As Integer = ContestBindingSource.Current("Cont_id")
'get the category of the contest
Me.CategoryTableAdapter.FillByContestID(Me.PSSDataSet.Category, Convert.ToInt32(contestID))
For Each Category As DataRow In Me.PSSDataSet.Category.Rows
Me.CriteriaTableAdapter.FillByCategoryID(Me.PSSDataSet.Criteria, Category("Cat_id"))
For Each Contestant As DataRow In Me.PSSDataSet.Contestant.Rows
For Each Criteria As DataRow In Me.PSSDataSet.Criteria.Rows
TransactionsTableAdapter.Insert(JudgeContestid, Contestant("Con_id"), Criteria("Cri_id"), 0)
Next
Next
Next
End Sub
Now my problem is, how can I populate the datagrid using the data recently made by MakeTransaction() function?

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