How to convert dbnull type to string - vb.net-2010

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.

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

System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'

System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
I have this error in this code how can I solve it?
Imports System.Data.OleDb
Public Class yenikayit
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim isimT As String = ""
Dim soyisimT As String = ""
Dim tcNoT As String = ""
Dim yasT As String = ""
Dim cinsiyetT As String = ""
Dim perNoT As String = ""
Dim egDurT As String = ""
Dim meslekT As String = ""
Dim telNoT As String = ""
Dim emailT As String = ""
isimT = TextBox1.Text
soyisimT = TextBox2.Text
tcNoT = TextBox3.Text
yasT = TextBox6.Text
cinsiyetT = ComboBox1.Text
perNoT = TextBox4.Text
egDurT = ComboBox2.Text
telNoT = TextBox5.Text
meslekT = TextBox10.Text
emailT = TextBox9.Text
Dim query As String = "INSERT INTO Personel (isim,soyisim,Yas,Cinsiyet,Alan,Egitim,TC,personel_id,tel_no,email) VALUES(isimT,soyisimT,yasT,cinsiyetT,meslekT,egDurT,tcNoT,perNoT,telNoT,emailT)"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MONSTER\Desktop\AGKS\AGKS\Database5.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Dim sonuc As Boolean
sonuc = cmd.ExecuteNonQuery()
If (sonuc = 1) Then
MsgBox("Girdiğiniz veriler kayıt olmuştur")
conn.Close()
End If
End Sub
End Class
this is the part of the code that give us error
Currently, your code does not add any parameter values to the command, hence the "No Values Given" error. The command doesn't recognize those names and assign them values just because you have declared them as variables above. You should make it clear that those are parameters in your sql query, and then set each parameter's value before executing the query:
Note that all instances of OleDbType.VarChar need to be replaced with the correct datatypes of your columns. I obviously have no way of knowing what types those columns are so I have just made them all VarChar, but you should adjust those to match your table schema.
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MONSTER\Desktop\AGKS\AGKS\Database5.accdb"
Dim query As String = "INSERT INTO Personel (isim,soyisim,Yas,Cinsiyet,Alan,Egitim,TC,personel_id,tel_no,email) " & _
"VALUES (#isimT,#soyisimT,#yasT,#cinsiyetT,#meslekT,#egDurT,#tcNoT,#perNoT,#telNoT,#emailT)"
Using conn As OleDbConnection = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
With cmd
.Parameters.Add("#isimT", OleDbType.VarChar).Value = TextBox1.Text
.Parameters.Add("#soyisimT", OleDbType.VarChar).Value = TextBox2.Text
.Parameters.Add("#yasT", OleDbType.VarChar).Value = TextBox6.Text
.Parameters.Add("#cinsiyetT", OleDbType.VarChar).Value = ComboBox1.Text
.Parameters.Add("#meslekT", OleDbType.VarChar).Value = TextBox10.Text
.Parameters.Add("#egDurT", OleDbType.VarChar).Value = ComboBox2.Text
.Parameters.Add("#tcNoT", OleDbType.VarChar).Value = TextBox3.Text
.Parameters.Add("#perNoT", OleDbType.VarChar).Value = TextBox4.Text
.Parameters.Add("#telNoT", OleDbType.VarChar).Value = TextBox5.Text
.Parameters.Add("#emailT", OleDbType.VarChar).Value = TextBox9.Text
End With
conn.Open()
Dim sonuc As Boolean
sonuc = cmd.ExecuteNonQuery()
If (sonuc = 1) Then
MsgBox("Girdiğiniz veriler kayıt olmuştur")
End If
conn.Close()
End Using
Ok, try something like this:
Dim query As String = "INSERT INTO Personel (isim,soyisim,Yas,Cinsiyet,Alan,Egitim,TC,personel_id,tel_no,email) "
query +="VALUES(#isimT,#soyisimT,#yasT,#cinsiyetT,#meslekT,#egDurT,#tcNoT,#perNoT,#telNoT,#emailT)"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MONSTER\Desktop\AGKS\AGKS\Database5.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
query.Parameters.AddWithValue("#isimT", TextBox1.Text)
cmd.Parameters.AddWithValue("#soyisimT", TextBox2.Text)
cmd.Parameters.AddWithValue("#tcNoT", TextBox3.Text)
cmd.Parameters.AddWithValue("#yasT", TextBox6.Text)
cmd.Parameters.AddWithValue("#cinsiyetT", ComboBox1.Text)
cmd.Parameters.AddWithValue("#perNoT", TextBox4.Text)
cmd.Parameters.AddWithValue("#egDurT", ComboBox2.Text)
cmd.Parameters.AddWithValue("#telNoT", TextBox5.Text)
cmd.Parameters.AddWithValue("#meslekT", TextBox10.Text)
cmd.Parameters.AddWithValue("#emailT", TextBox9.Text)
conn.Open()
Dim sonuc As Boolean
sonuc = cmd.ExecuteNonQuery()
If (sonuc = 1) Then
MsgBox("Girdiğiniz veriler kayıt olmuştur")
conn.Close()
End If
This should do the job. This should fix your exception.

Index out of range exception 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.

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