Why is my WHERE clause not working in SQL? - vb.net

Private Sub BTNupdate_Click(sender As Object, e As EventArgs) Handles BTNupdate.Click
con.Open()
Dim LRN As Integer = TextBoxLRN.Text
Dim FULLNAME As String = TextBoxFullName.Text
Dim GENDER As String = ComboBoxGen.SelectedItem
Dim COURSE As String = TextBoxCourse.Text
Dim SECTION As String = TextBoxSection.Text
query = "UPDATE StudentInfoTbl
SET [FULL NAME] = #FULLNAME, [GENDER] = #GENDER, [COURSE] = #COURSE,
[SECTION] = #SECTION
WHERE [LRN] = #LRN ;" --> 'HERE IS THE ERROR
cmd.Connection = con
cmd.CommandText = query
cmd.Parameters.AddWithValue("#LRN", TextBoxLRN.Text)
cmd.Parameters.AddWithValue("#FULL NAME", TextBoxFullName.Text)
cmd.Parameters.AddWithValue("#GENDER", ComboBoxGen.SelectedItem)
cmd.Parameters.AddWithValue("#COURSE", TextBoxCourse.Text)
cmd.Parameters.AddWithValue("#SECTION", TextBoxSection.Text)
cmd.ExecuteNonQuery()
MessageBox.Show(TextBoxLRN.Text & " Record hass been successfully updated!", "Record Saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
ClearTextBox()
BindData()
con.Close()
End Sub
my WHERE clause in SQL query is not being read but when I remove the WHERE clause, all the data from my data table are updated. I want to specify that LRN data will be updated.

Related

Using 2 combo boxes to populate a datagridview in VB.NET

I having problems understanding why my one of my comboboxes displays a filtered search but the other one doesn't, I am using the same code for both comboboxes but modified some SQL queries linked to my database. I have also noticed that when I remove or comment out the code for any one of the comboboxes the the filtered search happens for the one hasn't been commented or removed. I also used an "If, Else" statement but still doesn't work. I would also want for both comboboxes to be used to filter a datagridview. Just to keep in mind once the item is selected from the combobox a search button is pressed to filer/display data into the datagridview.
Kind Regards
Here is my code and form:
[Redundant Data being displayed] https://i.stack.imgur.com/JEQI4.png
[ComboBox Brand works as intended] https://i.stack.imgur.com/6YyBf.png
[ComboBox Category displays everything rather than displaying the category chosen] https://i.stack.imgur.com/oEfII.png
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
If Not CmbBrand.SelectedIndex & CmbCategory.SelectedIndex = Nothing Then
BrandDisplay()
ElseIf CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
CategoryDisplay()
ElseIf Not CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
End If
cn.Close()
End Sub
Private Sub BrandDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STBrand Like #BrandSearch"
.Parameters.AddWithValue("#BrandSearch", "%" & CmbBrand.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Brand from the drop down list", "Brand", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
Private Sub CategoryDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
```
It is a good idea to separate your User Interface code from you database code. Your event procedure code should be rather brief.
Declare your Connections, Commands and DataReaders in the method where they are used so they can be disposed. Using...End Using blocks do this for us; they also close the connection. Pass your connection string directly to the constructor of the connection.
We have a different CommandText and ParametersCollection for each possibility. For Sql Server use the Add method rather than AddWithValue.
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim dt = GetSearchData(CmbBrand.Text, CmbCategory.Text)
DGVRecord.DataSource = dt
End Sub
Private Function GetSearchData(Brand As String, Category As String) As DataTable
Dim dt As New DataTable
Dim sqlString = "Select * From From TblStock "
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand()
cmd.Connection = cn
If Not String.IsNullOrEmpty(Brand) AndAlso Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch And STBrand = #BrandSearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Brand) Then
cmd.CommandText = sqlString & "Where STBrand = #BrandSearch;"
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
Else
cmd.CommandText = sqlString & ";"
End If
cn.Open()
Using reader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Return dt
End Function
For better understanding you need to change those first "if... then... else...".
If the combobox is not selected it will have value -1 so you can do it like this:
Dim bBrandIsSelected as boolean = CmbBrand.SelectedIndex <> -1
Dim bCategoryIsSelected as boolean = CmbCategory.SelectedIndex <> -1
Now you can build the code more easily like:
If bBrandIsSelected AndAlso bCategoryIsSelected then
' do something
else
if bBrandIsSelected then
BrandDisplay()
else
if bCategoryIsSelected then
CategoryDisplay()
End if
End if
End if

Database locked in vb.net when trying to update data in vb.net

Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Comparing TimeoftheDay to a String

Error in Comparing Time to a String
Cdate is my previous code and i revise it to compareTime Can anyone
help me if the current expression to compare time is correct because
the message is "Contact your Administrator! Maybe your not
registered."
So the expression is still "false"
#Region "TIMER"
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
LBLDATE.Text = My.Computer.Clock.LocalTime.Date
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
LBLTIME.Text = TimeOfDay
End Sub
#End Region
Dim conn As OleDb.OleDbConnection = GetConnection()
Dim sql As String
Dim sql1 As String
Dim A As Integer
Dim result = Nothing
Dim compareTime As String = "7:01:00 PM"
' Dim amlate1 As String = "7:01:00 PM"
Dim remm1 As String
' If CDate(Form7TO3.LBLTIME.Text) >= CDate(amlate1) Then
If compareTime = DateTime.Now.ToString("h:mm:ss tt") Then
remm1 = "LATE"
Else
remm1 = "ON TIME"
End If
Try
sql1 = "SELECT * FROM DTR_REC WHERE MEM_CODES LIKE '" & Form7TO3.txtinput.Text & "' AND SDATE = '" & Form7TO3.LBLDATE.Text & "'"
Dim DA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql1, conn)
Dim DS As New DataSet
DA.Fill(DS, "dtrdb")
A = DS.Tables("dtrdb").Rows.Count
If A > 0 Then
MessageBox.Show("Sorry you Already finished Log in!")
Else
sql = "INSERT INTO DTR_REC (MEM_CODES, AM_IN, FIRST_AM_REMARK, SDATE) VALUES (#MEM_CODES, #AM_IN, #FIRST_AM_REMARK, #SDATE)"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDb.OleDbParameter("#MEM_CODES", Form7TO3.txtinput.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter(" #AM_IN", Form7TO3.LBLTIME.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter("#FIRST_AM_REMARK", remm1))
cmd.Parameters.Add(New OleDb.OleDbParameter("#SDATE", DateTime.Parse(Form7TO3.LBLDATE.Text)))
conn.Open()
cmd.ExecuteNonQuery()
If remm1 = "LATE" Then
MessageBox.Show("Hurry up your Late")
ElseIf remm1 = "ON TIME" Then
MessageBox.Show("Very good you come on time!")
End If
End If
clear()
Catch ex As Exception
Dim dgresult As DialogResult
Dim ms As String
ms = "Contact your Administrator! Maybe your not registered."
MessageBox.Show(ms, "Error in connection", MessageBoxButtons.OKCancel, _
MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2)
If dgresult = DialogResult.Yes Then
Form1.Show()
End If
End Try
Return result
Here's my current codes
Can anyone revise this codes
If the record is already exist a messagebox will appear saying "Sorry you finished log in"
otherwise it will save/add records on my database
(The problem is , if the records still exists it add/insert another the same record)
Dim conn As OleDb.OleDbConnection = GetConnection()
Dim sql As String
Dim sql1 As String
'Dim A As Integer
Dim result = Nothing
'Dim time_1 As String = DateTime.Parse("11:00:00 PM").ToString("T")
'Dim time_2 As String = DateTime.Now.ToString("T")
Dim remm1 As String
Dim PMOUT As String = "11:00:00 PM"
Dim str As String = "HH:mm:ss"
str = TimeOfDay()
' If DateTime.Now.TimeOfDay > amlate1.TimeOfDay Then
' If DateTime.Compare(time_1, time_2) > 0 Then
If str >= PMOUT Then
remm1 = "LATE"
Else
remm1 = "ON TIME"
End If
Try
conn.Open()
sql1 = "SELECT * FROM DTR_REC WHERE MEM_CODES = '" & Form11TO7.txtinput.Text & "' AND SDATE = #" & FormatDateTime(DateTime.Now, DateFormat.GeneralDate = DateFormat.ShortDate) & "#"
' Dim DA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql1, conn)
Dim cmd1 As New OleDb.OleDbCommand(sql1, conn)
'Dim DS As New DataSet
'DA.Fill(DS, "dtrdb")
'A = DS.Tables("dtrdb").Rows.Count
'If A > 0 Then
Using reader As OleDb.OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
'user already finished to time in
MessageBox.Show("Sorry you Already finished Log in!")
Else
sql = "INSERT INTO DTR_REC (MEM_CODES, PM_IN, FIRST_PM_REMARK, SDATE) VALUES (#MEM_CODES, #PM_IN, #FIRST_PM_REMARK, #SDATE)"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDb.OleDbParameter("#MEM_CODES", Form11TO7.txtinput.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter(" #PM_IN", str))
cmd.Parameters.Add(New OleDb.OleDbParameter("#FIRST_PM_REMARK", remm1))
cmd.Parameters.Add(New OleDb.OleDbParameter("#SDATE", FormatDateTime(DateTime.Now, DateFormat.GeneralDate = DateFormat.ShortDate)))
Dim icount As String
icount = cmd.ExecuteNonQuery()
MessageBox.Show(icount)
If remm1 = "LATE" Then
MessageBox.Show("Hurry up your Late")
ElseIf remm1 = "ON TIME" Then
MessageBox.Show("Very good you come on time!")
End If
End If
End Using
clear()
Catch ex As Exception
Dim dgresult As DialogResult
Dim ms As String
ms = "Contact your Administrator! Maybe your not registered."
'MessageBox.Show(ms = "Contact your Administrator! Maybe your not registered." & vbNewLine & ex.Message)
MessageBox.Show(ms, "Error in connection", MessageBoxButtons.OKCancel, _
MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2)
If dgresult = DialogResult.Yes Then
Form1.Show()
End If
'MessageBox.Show(ex.Message)
End Try
Return result

Issues with SQL parameters

I am trying to set employees for a company to 'present' if they clock-in/out on the program. The database has a field with the same name and uses a boolean value to store whether someone is or isn't present. I believe my SQL statement is correct. The issue that I continue to get is: "Additional information: No value given for one or more required parameters."
Here is the code that I am using to perform the UPDATE query:
Private Sub btnClockout_Click(sender As Object, e As EventArgs) Handles btnClockout.Click
'SelectedEmployee = lstClockin.FocusedItem.Text
'lblClockinStatusColor.BackColor = Color.Red
'btnClockout.Enabled = False
'btnClockin.Enabled = True
'lblClockinStatus.Text = "Employee is: Clocked Out"
'If txtInfoEmployeeID.Text = "" Then
' MsgBox("You need to select a employee to clock-out.", MsgBoxStyle.Exclamation)
'End If
con.ConnectionString = provider & datafile
con.Open()
sqlstatement = ("UPDATE [EmployeeAccounts] SET [Present] = False WHERE [EmployeeID] = '" & SelectedEmployee & "'")
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "ClockOutButton")
con.Close()
End Sub
I don't think there is any Boolean type in SQL database. You can use below code.
Private Sub btnClockout_Click(sender As Object, e As EventArgs) Handles btnClockout.Click
SelectedEmployee = lstClockin.FocusedItem.Text
'lblClockinStatusColor.BackColor = Color.Red
'btnClockout.Enabled = False
'btnClockin.Enabled = True
'lblClockinStatus.Text = "Employee is: Clocked Out"
'If txtInfoEmployeeID.Text = "" Then
' MsgBox("You need to select a employee to clock-out.", MsgBoxStyle.Exclamation)
'End If
con.ConnectionString = provider & datafile
con.Open()
sqlstatement = ("UPDATE [EmployeeAccounts] SET [Present] = 'False' WHERE [EmployeeID] = '" & SelectedEmployee & "'")
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "ClockOutButton")
con.Close()
End Sub

Passing Datagridview values to another form in VB.net

I am trying to pass datagrid values to another form by clicking a table row My question is , if SELECT statement is the right code?
click table row > display results to other form
Edit : I got it working now
this is my new code:
Dim selectQ As String = "SELECT FirstName, LastName, MI, DOB, Age, Gender, Dept, DEP, MStatus, Phone1, Phone2, Tel, Email, HomeAdd, StreetAdd, CityAdd, Region, Refname1, Refname2, Refnum1, Refnum2 FROM Empinfo WHERE ID = " & Form4.MetroGrid1.CurrentRow.Cells(0).Value.ToString
Before:
Dim selectQ As String = "SELECT FirstName, LastName, MI, DOB, Age,
Gender, Dept, DEP, MStatus
FROM Empinfo
WHERE ID = '" & Form4.MetroGrid1.CurrentRow.Cells(0).Selected & "'"
'My full Code:
Private Sub Form6_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim constr As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\DB1.accdb"
Dim con As New OleDbConnection(constr)
Dim datareader As OleDbDataReader
Dim selectQ As String = "SELECT FirstName, LastName, MI, DOB, Age, Gender, Dept, DEP, MStatus FROM Empinfo WHERE ID = '" & Form4.MetroGrid1.CurrentRow.Cells(0).Selected & "'"
Dim cmd As New OleDbCommand(selectQ, con)
con.Open()
datareader = cmd.ExecuteReader
If datareader.HasRows Then
datareader.Read()
MetroTextBox1.Text = datareader(0).ToString
MetroTextBox2.Text = datareader(1).ToString
MetroTextBox3.Text = datareader(2).ToString
MetroDateTime1.Text = datareader(3).ToString
MetroComboBox1.Text = datareader(4).ToString
MetroComboBox2.Text = datareader(5).ToString
MetroComboBox3.Text = datareader(6).ToString
MetroDateTime2.Text = datareader(7).ToString
MetroComboBox5.Text = datareader(8).ToString
datareader.Close()
Else
MetroFramework.MetroMessageBox.Show(Me, "There is no data present", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
con.Close()
Catch ex As Exception
MsgBox(ex.ToString)
'MetroFramework.MetroMessageBox.Show(Me, ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
i get data type mismatch when i run the program
While it's legal to call Form4.MetroGrid1.CurrentRow.Cells(0).Selected it might not be accessing the instance of Form4, plus I don't think .Selected is the value you need for the statement. It would be better to make a Sub New for Form6 that passes that data to it.
Public Class Form6
Private id As String
Public Sub New(id As String)
Me.id = id
End Sub
Private Sub Form6_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim constr As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\DB1.accdb"
Dim con As New OleDbConnection(constr)
Dim datareader As OleDbDataReader
Dim selectQ As String = "SELECT FirstName, LastName, MI, DOB, Age, Gender, Dept, DEP, MStatus FROM Empinfo WHERE ID = '" & id & "'"
Dim cmd As New OleDbCommand(selectQ, con)
con.Open()
datareader = cmd.ExecuteReader
If datareader.HasRows Then
datareader.Read()
MetroTextBox1.Text = datareader(0).ToString
MetroTextBox2.Text = datareader(1).ToString
MetroTextBox3.Text = datareader(2).ToString
MetroDateTime1.Text = datareader(3).ToString
MetroComboBox1.Text = datareader(4).ToString
MetroComboBox2.Text = datareader(5).ToString
MetroComboBox3.Text = datareader(6).ToString
MetroDateTime2.Text = datareader(7).ToString
MetroComboBox5.Text = datareader(8).ToString
datareader.Close()
Else
MetroFramework.MetroMessageBox.Show(Me, "There is no data present", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
con.Close()
Catch ex As Exception
MsgBox(ex.ToString)
'MetroFramework.MetroMessageBox.Show(Me, ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class
Usage:
Dim f6 As New Form6(MetroGrid1.CurrentRow.Cells(0).Value.ToString)
f6.Show()