Index out of range exception vb.net - vb.net

I'm currently working on a project where I need to insert/search/add to/from M.S access datatable to textboxes.
Search is based on id and while trying to insert data onto textboxes I get an error
index out of range exception: Mobile Number"
cn.Open()
comand.Connection = cn
comand.CommandText = "SELECT * from Address_table where ID=#id"
comand.Parameters.Add("#id", OleDbType.Numeric).Value = TextBox1.Text
Dim dr As OleDbDataReader = comand.ExecuteReader()
Do While dr.Read() = True
TextBox2.Text = dr("Name")
TextBox3.Text = dr("House Name")
TextBox4.Text = dr("City")
TextBox5.Text = dr("Mobile Number".ToString)
TextBox6.Text = dr("PinCode".ToString)
TextBox7.Text = dr("Email")
Loop
If dr.Read() = False Then
MessageBox.Show("enter a valid id")
End If
dr.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
cn.Close()
Any help appreciated. Thank you in Advance

This:
TextBox5.Text = dr("Mobile Number".ToString)
Should be this:
TextBox5.Text = dr("Mobile Number").ToString
And really, I expect that column name also isn't quite right. You may need to escape the space somehow.

Related

VB.net and SQL .... For multiple read of database table

Im am currently coding an handsfree RFID attendance monitoring system where i could just swipe and record details automatically...
I've been in trouble about this piece of code where i need to fetch a table and another table inorder to check if there is an existing record in table1 as the details and table2 as a record in in/out. I wanted it as much as possible to be able to be in a 1 while loop
**
I kept getting this error **
Invalid attempt to access a field before calling Read()
`
Private Sub TextBox7_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox7.KeyDown
If e.KeyCode = Keys.Enter Then
'Dim idnum = Val(TextBox7.Text
Dim statu As String = ""
Dim idnum = (TextBox7.Text)
Dim record As String = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
ConnectToDB()
sql = "select * from rfidmaintest.student_details_dub where f9 = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
TextBox2.Text = (dr("f2"))
TextBox3.Text = (dr("f9"))
TextBox4.Text = (dr("f4"))
TextBox5.Text = (dr("f14"))
TextBox6.Text = (dr("f3"))
TextBox7.Clear()
dr.Close()
cn.Close()
'ANOTHER FETCH
ConnectToDB()
sql = "select * from rfidmaintest.monitoring where id_num = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
**Invalid attempt to access a field before calling Read()**
If (dr("entry_record")) = String.Empty Then
status.Text = "IN"
End If
If status.Text = "IN" Then
status.Text = (dr("entry_record"))
record = "OUT"
ElseIf status.Text = "OUT" Then
record = "IN"
ElseIf status.Text = String.Empty Then
record = "IN"
End If
End While
dr.Close()
cn.Close()
`
I tried to call the table
You need another dr.read for the second query or you can use another reader, for example like dr2.read.
Your first While dr.read already closed with dr.close, you need to reopen the reader to continue to read the second query

How to Create Buffer in-order to avoid duplication of IN and OUT attendance

Im trying to make an IN and OUT, and Have done the whole program with it's database... Now the last is how do I make a time buffer inorder not to get a duplicate record with the same time.
this is the code that I have done to create the running code... Question is How do I make the buffer. I have search through the internet yet I couldn't find the suitable method
ConnectToDB()
sql = "select * from rfidmaintest.student_details_dub where f9 = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
TextBox2.Text = (dr("f2"))
TextBox3.Text = (dr("f9"))
TextBox4.Text = (dr("f4"))
TextBox5.Text = (dr("f14"))
TextBox6.Text = (dr("f3"))
TextBox7.Clear()
status.Text = "IN"
End While
dr.Close()
cn.Close()
'ANOTHER FETCH
ConnectToDB()
sql = "select * from rfidmaintest.monitoring where id_num = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
If (dr("entry_record")) = "IN" Then
record = "OUT"
ElseIf (dr("entry_record")) = "OUT" Then
record = "IN"
ElseIf (dr("entry_record")) = String.Empty Then
record = "IN"
End If
status.Text = (record)
End While
dr.Close()
cn.Close()
ConnectToDB()
sql = "insert into monitoring (id_num, fname, lname, status, entry_record, floor_level, date) VALUES (#num, #name, #lname, #stat, #record, #lev,#date)"
cmd = New MySqlCommand(sql, cn)
With cmd
.Parameters.AddWithValue("#num", idnum)
.Parameters.AddWithValue("#name", TextBox2.Text)
.Parameters.AddWithValue("#lname", TextBox6.Text)
.Parameters.AddWithValue("#stat", TextBox5.Text)
.Parameters.AddWithValue("#lev", levellock.sharevalue)
.Parameters.AddWithValue("#record", status.Text)
.Parameters.AddWithValue("#date", Date.Now)
.ExecuteReader()
End With
MsgBox("Details has been saved!", vbInformation, "Saved")
cmd = Nothing
dr.Close()
cn.Close()
I don't know if this what you meant because your english is horrible.
How about in the Date.Now you also include second so it become like this
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
y = Year
M = Month
d = Date
H = Hour
m = Minute
s = Second

VB.NET:Updating record in Ms Access

I am creating an employee timing sheet in which they have to insert their timings through pressing timein and timeout buttons. For timein I am creating a new record in database, for that person, and for timeout I am using UPDATING command to update that existing record. Here is my code:
Dim cb As New OleDb.OleDbCommandBuilder(ssda)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim str As String
str = "UPDATE emp_timing SET emp_timing.emp_timeout = '" & OnlyTime & "' WHERE (((emp_timing.emp_code)='" & TextBox1.Text & "') AND ((emp_timing.day)=" & Now.ToString("MM/dd/yyyy") & "))"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
Catch ex As Exception
MsgBox(ex.Message)
End Try
My code is working fine but the problem is that it is not updating records in database.
Datatype for fields in Access:
emp_code = Number, emp_timeout = Text, day = Date/Time.
As usual this is caused by your code not using the Parameters collection to pass values to the database engine. This is not really understood until you hit a conversion problem as always happens with dates
str = "UPDATE emp_timing SET emp_timeout = #p1 " & _
"WHERE emp_code = #p2 AND day = #p3"
Using con = new OleDbConnection( dbProvider & dbSource)
Using cmd = New OleDbCommand(str, con)
con.Open()
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = OnlyTime
cmd.Parameters.Add("#p2", OleDbType.Integer).Value = Convert.ToInt32(TextBox1.Text)
cmd.Parameters.Add("#p3", OleDbType.Date).Value = new DateTime(Now.Year, Now.Month, Now.Day)
Try
Dim rowsAdded = cmd.ExecuteNonQuery()
if rowsAdded > 0 Then
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using

How to convert dbnull type to string

If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
sql = "SELECT *FROM tbL_books_transactions WHERE transactionID LIKE '%" & TextBox8.Text & "%'"
cmd = New MySqlCommand(sql, conn)
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.Read = True Then
TextBox4.Text = CType(dr("AccessionNo"), String)
TextBox7.Text = CType(dr("BookTitle"), String)
TextBox11.Text = CType(dr("DateBorrowed"), String).ToString()
TextBox3.Text = CType(dr("userID"), String)
TextBox10.Text = CType(dr("userName"), String)
Else
MsgBox("No Student Record Exist")
End If
conn.Close()
This is a simple way to convert a column that contains a null value to something that you are able to work with your textboxes
Dim pos = dr.GetOrdinal("AccessioNo")
TextBox4.Text = if(dr.IsDbNull(pos), string.Empty, dr.GetString(pos))
In this example, first retrieve the ordinal position of the column that you are interested to read. Then use that value to call IsDbNull and put everything inside a ternary operator If the valus is null return an empty string otherwise the content of the field with GetString.

autofilling textboxes with database data based on a primary key entry into another textbox

i have the code below, it works fine but whenever i insert a student number that does not exist in the table, the rest of the textboxes will keep displaying data from the previous existing entry. This happens even when the i delete everything in the student number textbox.
how can i change it such that the rest of the textboxes are cleared in case the student number textbox is blank or contains a student number that does not exist in the database?
Thanks in advance.
' Try
Dim mycommand As SqlCommand = New SqlCommand()
Dim datareader As SqlDataReader = Nothing
myconnection.Open()
Dim query As String
query = " select StudentNo,Fullname,Year,Term,Class from StudentRegistration where StudentNo = '" & TxtStudentNo.Text & "' and (class = 'Senior 5A' or Class ='Senior 5S' or Class='Senior 6A' or class='Senior1 6S')"
mycommand = New SqlCommand(query, myconnection)
datareader = mycommand.ExecuteReader()
While datareader.Read
If datareader IsNot Nothing Then
' TxtStudentNo.Text = datareader.Item("StudentNo")
TxtName.Text = datareader.Item("FullName")
TxtYear.Text = datareader.Item("Year")
TxtTerm.Text = datareader.Item("Term")
TxtClass.Text = datareader.Item("Class")
End If
End While
myconnection.Close()
' Catch ex As Exception
'MessageBox.Show(ex.Message)
' End Try`
Add an else condition to reader and clear text boxes in that module.
While datareader.Read
If datareader IsNot Nothing Then
' TxtStudentNo.Text = datareader.Item("StudentNo")
TxtName.Text = datareader.Item("FullName")
TxtYear.Text = datareader.Item("Year")
TxtTerm.Text = datareader.Item("Term")
TxtClass.Text = datareader.Item("Class")
else
TxtName.Text = ""
TxtYear.Text = ""
TxtTerm.Text = ""
TxtClass.Text = ""
End If
hope theres no big deal more than this.
I finally changed my code to the one below and it's doing exactly what i want.
Private Sub getData()
Dim dt As New DataTable()
myconnection.Open()
Dim Mycommand As New SqlCommand("select Fullname,Year,Term,Class from StudentRegistration where StudentNo = '" & TxtStudentNo.Text & "'", myconnection)
Dim sqlDa As New SqlDataAdapter(Mycommand)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
TxtName.Text = dt.Rows(0)("FullName").ToString()
TxtYear.Text = dt.Rows(0)("Year").ToString()
Else
TxtName.Text = ""
TxtYear.Text = ""
End If
myconnection.Close()
End Sub