show multiple data on rcihtextbox from database column error - vb.net

What's wrong with my code? the error happens on UPDATE block "
If reader1.Read() Then
rtbURThirdMolar.Text = reader1.Item("Up_Right_3rd_Molar")" Conversion from type 'DBNull' to type 'String' is not valid
Private Sub txtURThirdMolar_KeyDown(sender As Object, e As KeyEventArgs) Handles txtURThirdMolar.KeyDown
MySqlConn.open()
If e.KeyCode = Keys.Enter Then
query1 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd1 = New MySqlCommand(query1, MySqlConn)
reader = cmd1.ExecuteReader
If reader.HasRows Then
Dim i As Integer
With cmd
.Connection = MySqlConn
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar = concat('" & txtURThirdMolar.Text & Environment.NewLine & "',Up_Right_3rd_Molar) WHERE Patient_ID_Number = " & lblID.Text
reader.Close()
i = .ExecuteNonQuery
End With
If i > 0 Then
MsgBox("Updated!", MsgBoxStyle.Information, "Success")
txtURThirdMolar.Text = ""
Dim query2 As String
Dim reader1 As MySqlDataReader
Dim cmd2 As MySqlCommand
query2 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd2 = New MySqlCommand(query2, MySqlConn)
reader1 = cmd2.ExecuteReader
If reader1.Read() Then
rtbURThirdMolar.Text = reader1.Item("Up_Right_3rd_Molar") 'THIS IS WHERE THE ERROR OCCURS
End If
Else
MsgBox("Failed", MsgBoxStyle.Information, "Failed")
End If
Else
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO teethhistory (Patient_ID_Number, Fullname, Up_Right_3rd_Molar )" &
"VALUES ('{0}' ,'{1}' ,'{2}')",
lblID.Text,
lblFullname.Text,
txtURThirdMolar.Text)
reader.Close()
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Saved!", MsgBoxStyle.Information, "Success")
txtURThirdMolar.Text = ""
Dim query2 As String
Dim reader2 As MySqlDataReader
Dim cmd2 As MySqlCommand
query2 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd2 = New MySqlCommand(query2, MySqlConn)
reader2 = cmd2.ExecuteReader
If reader2.Read() Then
rtbURThirdMolar.Text = reader2.Item("Up_Right_3rd_Molar")
End If
Else
MsgBox("Saving failed.", MsgBoxStyle.Critical, "Failed")
End If
End If
End If
MySqlConn.close()
End Sub

use
rtbURThirdMolar.Text = reader1.Item("Up_Right_3rd_Molar").ToString
this is because the item you are referencing is NULL.

Related

VB.net and DATABASE. i Kept getting an record without an Entry Level record (IN)

i kept getting an record without an Entry Level record (IN) that supposably will have an IN(database record) instead of NOTHING... However after it was scanned after another try only when IN is found in the database.... Overall I will just make an details but empty entry_record which is incomplete
enter image description here
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()
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()
End If
End Sub
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 status.Text = "IN" Then
'record = "OUT"
' ElseIf status.Text = "OUT" Then
' record = "IN"
' ElseIf status.Text = String.Empty Then
' record = "IN"
' End If
'status.Text = (record)
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()
stated the STATUS as IN

update data and image using 1 button, error data not update if insert same data in combobox

no update if same data combobox
Cmd = New SqlCommand("Select * from tbl_image where [Nama Barang]= #Nama_Barang ", Conn)
Cmd.Parameters.AddWithValue("#Nama_Barang", ComboBox1.Text)
RD = Cmd.ExecuteReader
RD.Read()
If RD.HasRows Then
Call Koneksi()
Dim edit As String = "Update tbl_image set Jumlah = #jumlah, [Stok Barang] =#Stok_Barang, Gambar = #Gambar where Kode = #Kode or [Nama Barang] = #Nama_Barang "
Cmd.Parameters.AddWithValue("#Kode", TextBox1.Text)
Cmd.Parameters.AddWithValue("#Nama_Barang", ComboBox1.Text)
Cmd.Parameters.AddWithValue("#Jumlah", TextBox2.Text)
Cmd.Parameters.AddWithValue("#Stok_Barang", TextBox3.Text)
Dim Images As SqlParameter = New SqlParameter("#Gambar", SqlDbType.Image)
Images.Value = Dgambar
Cmd.Parameters.Add(Images)
Cmd.ExecuteNonQuery()
'MsgBox("Data Berhasil Di Update")
'cmd.Dispose()
Else
Dim simpan As String = "INSERT INTO tbl_image VALUES( #Kode,#Nama_Barang, #Jumlah, #Stok_Barang, #Gambar) "
'Dim simpan As String = "INSERT INTO tbl_image VALUES( '" & TextBox1.Text & "','" & ComboBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "', #Gambar) "
Cmd = New SqlCommand(simpan, Conn)
Cmd.Parameters.AddWithValue("#Kode", TextBox1.Text)
Cmd.Parameters.AddWithValue("#Nama_Barang", ComboBox1.Text)
Cmd.Parameters.AddWithValue("#Jumlah", TextBox2.Text)
Cmd.Parameters.AddWithValue("#Stok_Barang", TextBox3.Text)
Dim MemoryStream As New MemoryStream
PictureBox1.Image.Save(MemoryStream, System.Drawing.Imaging.ImageFormat.Bmp)
Dim Dgambar As Byte() = MemoryStream.GetBuffer
Dim Images As New SqlParameter("#Gambar", SqlDbType.Image)
Images.Value = Dgambar
Cmd.Parameters.Add(Images)
Cmd.ExecuteNonQuery()
MsgBox("Data Berhasil Di Simpan")
Dim edit As String = "Update tbl_image set Jumlah = #jumlah, [Stok Barang] =#Stok_Barang, Gambar = #Gambar where Kode = #Kode or [Nama Barang] = #Nama_Barang "

da.fill incorrect syntax near ')'

I'm having a problem from the line
da.Fill(ds, "Employee")
and I don't have any clue to solve this. Can anyone help?
This is my actual code:
Private Sub btnsearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsearch.Click
Dim da As New SqlClient.SqlDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
If txtssn.Text = "" Then
MsgBox("Please input SSN.", MsgBoxStyle.Exclamation, "Company Records - Employee")
Else
con.Open()
Dim cmd As New SqlCommand("SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "')", con)
da.SelectCommand = cmd
da.Fill(ds, "Employee")
dt = ds.Tables("Employee")
If (dt.Rows.Count > 0) Then
Me.txtfname.Text = dt.Rows(0).Item(1)
Me.txtmi.Text = dt.Rows(0).Item(2)
Me.txtlname.Text = dt.Rows(0).Item(3)
Me.dtpbdate.Text = dt.Rows(0).Item(5)
Me.txtaddress.Text = dt.Rows(0).Item(6)
Me.cmbsex.Text = dt.Rows(0).Item(7)
Me.txtsalary.Text = dt.Rows(0).Item(8)
Me.cmbsuperssn.Text = dt.Rows(0).Item(9)
'Me.cmbdept.Text =
btnedit.Enabled = True
btndelete.Enabled = True
editable()
Else
MsgBox("Record Not Found", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Company Records - Employee")
End If
con.Close()
End If
Remove the closing parantheses since that's a SELECT not an INSERT:
"SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "'"
However, i would always use sql-parameters to prevent sql-injection.
Using con As New SqlConnection("ConenctionString")
Using da As New SqlDataAdapter("SELECT * FROM [Employee] WHERE [Ssn] = #SSN", con)
da.SelectCommand.Parameters.Add("#SSN", SqlDbType.VarChar).Value = txtssn.Text
da.Fill(ds, "Employee")
End Using
End Using
Remove the trailing ) from your SQL statement.
"SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "'"
Also see why you shouldn't be doing it in the first place.
Their is syntax error near your SQLstatement so you need to remove an unwanted ( to make this statement workable.
Dim cmd As New SqlCommand("SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "'", con)

Combo box joining two tables from SQL Server database

I'm trying to show 2 tables from a SQL Server database, but nothing is displayed
Please help!!!!!!!
MysqlConn = New SqlConnection
MysqlConn.ConnectionString =
"Data Source=SABAHALI-SHEIKH;Initial Catalog=md_1103763;Integrated Security=True"
Dim READER As SqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT [customerID], [firstname], [surname], [contactnumber], [emailaddress] FROM md_1103763.dbo.customer where firstname='" & ComboBox1.Text & "'"
Query = "SELECT [bookingID], [pickupaddress], [destinationaddress], [datebooked], [timebooked] FROM md_1103763.dbo.booking where bookingID='" & ComboBox1.Text & "'"
COMMAND = New SqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
TextBox1.Text = READER.GetInt32(READER.GetOrdinal("customerID"))
TextBox2.Text = READER.GetString(READER.GetOrdinal("firstname"))
TextBox3.Text = READER.GetString(READER.GetOrdinal("surname"))
TextBox4.Text = READER.GetString(READER.GetOrdinal("contactnumber"))
TextBox5.Text = READER.GetString(READER.GetOrdinal("emailaddress"))
TextBox8.Text = READER.GetString(READER.GetOrdinal("bookingID"))
TextBox6.Text = READER.GetString(READER.GetOrdinal("pickupaddress"))
TextBox7.Text = READER.GetString(READER.GetOrdinal("destinationaddress"))
DateTimePicker1.Text = READER.GetString(READER.GetOrdinal("datebooked"))
DateTimePicker2.Text = READER.GetString(READER.GetOrdinal("timebooked"))
End While
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
You can Try This with change
this code
MysqlConn = New SqlConnection
MysqlConn.ConnectionString =
"Data Source=SABAHALI-SHEIKH;Initial Catalog=md_1103763;Integrated Security=True"
Dim READER As SqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT md_1103763.dbo.customer.customerID, md_1103763.dbo.customer.firstname, md_1103763.dbo.customer.surname,"&"md_1103763.dbo.customer.contactnumber, md_1103763.dbo.customer.emailaddress,"&
"md_1103763.dbo.booking.bookingID, md_1103763.dbo.booking.pickupaddress, md_1103763.dbo.booking.destinationaddress," &
"md_1103763.dbo.booking.datebooked, md_1103763.dbo.booking.timebooked FROM md_1103763.dbo.customer,md_1103763.dbo.booking "&
" where firstname='" & ComboBox1.Text & "'" +" And bookingID='" & ComboBox1.Text & "'"
COMMAND = New SqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
TextBox1.Text = READER.GetInt32(READER.GetOrdinal("customerID"))
TextBox2.Text = READER.GetString(READER.GetOrdinal("firstname"))
TextBox3.Text = READER.GetString(READER.GetOrdinal("surname"))
TextBox4.Text = READER.GetString(READER.GetOrdinal("contactnumber"))
TextBox5.Text = READER.GetString(READER.GetOrdinal("emailaddress"))
TextBox8.Text = READER.GetString(READER.GetOrdinal("bookingID"))
TextBox6.Text = READER.GetString(READER.GetOrdinal("pickupaddress"))
TextBox7.Text = READER.GetString(READER.GetOrdinal("destinationaddress"))
DateTimePicker1.Text = READER.GetString(READER.GetOrdinal("datebooked"))
DateTimePicker2.Text = READER.GetString(READER.GetOrdinal("timebooked"))
End While
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try

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?