Auto refresh DataGridView after update - vb.net

I want to get auto refresh Datagridview after update
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CON As SqlConnection
CON = New SqlConnection("Data Source=.;Initial Catalog=PantienDatabase;Integrated Security=True")
CON.Open()
Try
cmd = New SqlCommand
cmd.Connection = CON
cmd.CommandText = "UPDATE Patient_Detail SET Name ='" & TextBoxName.Text & "',Age = '" & TextBoxAge.Text & "',Sex = '" & TextBoxSex.Text & "',Address = '" & TextBoxAddress.Text & "',Check_In = '" & TextBoxCHiN.Text & "',Check_In_Illness = '" & TextBoxCHinL.Text & "',Sevice = '" & TextBoxService.Text & "',Check_out_Illness = '" & TextBoxCHoutL.Text & "',Check_out = '" & TextBoxCHout.Text & "',Transfer = '" & TextBoxTransfer.Text & "',Patient_result = '" & ComboBoxPtr.Text & "' WHERE ID = '" & TextBoxid.Text & "' "
//'cmd.CommandText = "UPDATE Patient_Detail SET Name = #Name, Age = #Age, Sex = #Sex, Address = #Address, Check_In = #Check_In, Check_In_Illness =#Check_in_illness, Sevice =#Service, Check_out_Illness =#Check_out_Illness, Check_out = #Check_out ,Transfer = #Transfer, Patient_result = #Pantient_result WHERE ID = #ID '
cmd.ExecuteNonQuery()
DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

In this case you need to rebind the data in DataGridView Like :
Dim conn As New MySqlConnection(My.Settings.myConn)
Dim da As New MySqlDataAdapter
Dim ds As New DataSet
Dim str1 As String = "select * from Patient_Detail "
da.SelectCommand = New MySqlCommand(str1, conn)
da.Fill(ds)
conn.Close()
DataGridView1.DataSource = ds.Tables(0)

Related

VB.net Load(cmd.ExecuteReader)

I have a function which i am getting syntax Error which I am using the same copy in other without any error .I am trying to open an Access table and read line by line and do some updates on it .
Function FlattenTable(Current As String, Freezefrom As Date, DateRef As Date, db As String)
Dim date1 As Date
Dim sql1 As String
Dim FreezeHrs As Double
Dim FreezeLnds As Long
Dim rs1 As DataTable
Dim cmd As OleDb.OleDbCommand
Dim con As New OleDb.OleDbConnection With {
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & db
}
con.Open()
If Freezefrom > DateRef Then
date1 = Freezefrom
Else
date1 = DateRef
End If
sql1 = "SELECT * FROM [Hours & Landings & Cycles] WHERE [A/C] = '" & Current & "' [DATE]= " & date1 & ""
cmd = New OleDbCommand(sql1, con)
rs1 = New DataTable
rs1.Load(cmd.ExecuteReader)
FreezeHrs = rs1.Rows.Item(0).Item(3)
FreezeLnds = rs1.Rows.Item(0).Item(4)
' "UPDATE [Hours & Landings & Cycles] SET [Code] = 'X' WHERE [A/C] = '" & Current & "' AND [Date]>=" & ActualEIS & " AND [Date]<=#" & DateValue(Format("{0:MM/dd/yyyy}", EndDate)) & "#"
sql1 = "UPDATE [Hours & Landings & Cycles] SET [HRS] = '" & FreezeHrs & "' WHERE [A/C] = '" & Current & "' AND [DATE]>='" & date1 & "'"
cmd = New OleDbCommand(sql1, con)
cmd.ExecuteNonQuery()
End Function
rs1.Load(cmd.ExecuteReader) is a data table reader

trying to update a passowrd and username in database i get operator error

Imports System.Data.OleDb
Imports System.Data
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ran As New Random
TextBox2.Text = ran.Next(1, 8)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Or MaskedTextBox3.Text = "" Then
MsgBox("Please fill all text boxes With the required info")
Else
Dim cmd As OleDbCommand
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =C:\users\nikh8610\Documents\users.accdb")
Dim str As String
con.Open()
str = "UPDATE users SET username = '" & TextBox1.Text & "'WHERE (ID = '" & TextBox2.Text & "') AND password='" & MaskedTextBox3.Text & "' WHERE (ID = '" & TextBox2.Text & "')"
cmd = New OleDbCommand(str, con)
cmd.ExecuteNonQuery()
con.Close()
End If
End Sub
End Class
Your query isn't valid. You are using two WHERE parts on the query. Try the following:
str = "UPDATE users SET username = '" & TextBox1.Text & "' WHERE ID = '" & TextBox2.Text & "' AND password='" & MaskedTextBox3.Text & "'"
You also don't UPDATE the password of the user. You can use something like the following to UPDATE the username and password.
str = "UPDATE users SET username = '" & txtUsername.Text & "', password = '" & txtNewPassword.Text & "' WHERE ID = '" & txtUserID.Text & "' AND password = '" & txtOldPassword.Text & "'"
You should also use prepared statements to UPDATE the user information:
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = con
cmd.CommandText = "UPDATE users SET username = ?, password = ? WHERE ID = ? AND password = ?"
cmd.Parameters.Add("NewUsername", OleDbType.VarWChar, 50)
cmd.Parameters.Add("NewPassword", OleDbType.VarWChar, 50)
cmd.Parameters.Add("UserID", OleDbType.Long)
cmd.Parameters.Add("OldPassword", OleDbType.VarWChar, 50)
cmd.Parameters(0).Value = txtNewUsername.Text
cmd.Parameters(1).Value = txtNewPassword.Text
cmd.Parameters(2).Value = txtUserID.Text
cmd.Parameters(3).Value = txtOldPassword.Text
cmd.Prepare()
cmd.ExecuteNonQuery()

Searching multiple tables in Access vb.net

I have a search button which looks up for data only in tblDopage but there is a field strMatrice in this table that is linked to table tblMatrice. So if the user is searching for Matrice I should retrieve Matrice from tblMatrice and innerjoin it with tblDopage on strMatrice, it's like a search inside search and the result of searching for matrice is more than 1 result so that I have many results which i should link them with tblDopage to display the final result. What shall i do, I spended 3 days searching for a solution.
I retrieved strMatrice from tblMatrice and populated a dataset with the result but I don't know how to innerjoin between a dataset and table in the database which is the tblDopage
Help is very appreciated, Thank you in advance
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim sql = "SELECT * from tblDopages WHERE "
cmd = New OleDbCommand(Sql, myConnection)
Dim da As OleDbDataAdapter
If CKBrefech.Checked = True Then
sql = sql & "strRefEch = '" & TBrefech.Text & "' AND "
End If
If CKBmethode.Checked = True Then
sql = sql & "strMethode = '" & CBmethode.Text & "' AND "
End If
If CKBpurif.Checked Then
sql = sql & "strPurif = '" & CBpurif.Text & "' AND "
End If
If CKBmatrice.Checked Then
sql = sql & "strMatrice = '" & CBmatrice.Text & "' AND "
End If
If CKBmol.Checked Then
sql = sql & "strMolecule = '" & CBmol.Text & "' AND "
End If
If CKBechprep.Checked Then
sql = sql & "datDatePrepa >= #DatPrepa AND "
cmd.Parameters.Add("#DatPrepa", OleDbType.Date).Value = DTPechprep.Value.Date
End If
If CKBechau.Checked Then
sql = sql & "datDatePrepa <= #Datau AND "
cmd.Parameters.Add("#Datau", OleDbType.Date).Value = DTPechau.Value.Date
End If
If CKBtrigprepa.Checked = True Then
sql = sql & "strTrigPrepa = '" & TBtrigprepa.Text & "' AND "
End If
If CKBtriganaly.Checked = True Then
sql = sql & "strTrigAnaly = '" & TBtrigAnaly.Text & "' AND "
End If
If CKBappar.Checked = True Then
sql = sql & "strNomTech = '" & CBappar.Text & "' AND "
End If
If CKBnumappar.Checked = True Then
sql = sql & "[strEquip(Appareil)] = '" & CBnumappar.Text & "' AND "
End If
If CKBteneurmini.Checked = True Then
sql = sql & "dblDopage >= " & TBteneurmini.Text & " AND "
End If
If CKBteneurmax.Checked = True Then
sql = sql & "dblDopage <= " & TBteneurmax.Text & " AND "
End If
'if referentiel is enabled
myConnection.Close()
If CKBnomref.Checked Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
'Get IDref from table tblRefMatDetails and then make an innerjoin with tblRefMatrice to retrieve the matrice and insert it into the search query of tblDopages
Dim query = "select distinct a.strMatrice from tblRefMatrice a INNER JOIN tblRefMatDetails b on a.intIDref=b.intIDRef where "
cmd = New OleDbCommand(query, myConnection)
Try
If CKBnomref.Checked Then
query = query & "b.strReferentiel = '" & CBnomref.Text & "' AND "
End If
If CKBniv1.Checked Then
query = query & "b.strNIveau1 = '" & CBniv1.Text & "' AND "
End If
If CKBniv2.Checked Then
query = query & "b.strNiveau2 = '" & CBniv2.Text & "' AND "
End If
If CKBniv3.Checked Then
query = query & "b.strNiveau3 = '" & CBniv3.Text & "' AND "
End If
If CKBniv4.Checked Then
query = query & "b.strNiveau4 = '" & CBniv4.Text & "' AND "
End If
' Remove the last AND if any ....'
If query.EndsWith(" AND ") Then
query = query.Substring(0, query.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If query.EndsWith(" WHERE ") Then
query = query.Substring(0, query.Length - 7)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
cmd.CommandText = query
cmd.Connection = myConnection
Dim MyDataTable As New DataTable
Dim da As New OleDbDataAdapter(query, myConnection)
da.Fill(MyDataTable)
Dim row As DataRow
For Each row In MyDataTable.Rows
Dim strMatrice As String
strMatrice = row("strMatrice")
Next row
DataGridView2.DataSource = MyDataTable
'to focus on first row of DGV after populating it
DataGridView2.Rows(0).Selected = True
myConnection.Close()
Dim matrice As String
For x As Integer = 0 To DataGridView2.Rows.Count - 2
matrice = DataGridView2.Rows(x).Cells(0).Value
sql = sql & " strMatrice = '" & matrice.ToString & "' AND "
Dim row As DataRow
For Each row As DataRow In MyDataTable.Rows
matrice = row.Item("Detail")
Next row
Next
End If
' Remove the last AND if any ....'
If sql.EndsWith(" AND ") Then
sql = sql.Substring(0, sql.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If sql.EndsWith(" WHERE ") Then
sql = sql.Substring(0, sql.Length - 7)
End If
' cmd = New OleDbCommand(sql, myConnection)
cmd.CommandText = sql
cmd.Connection = myConnection
Dim MyDataSet As New DataSet
da = New OleDbDataAdapter(sql, myConnection)
da.SelectCommand = cmd
da.SelectCommand.Parameters.Add(New OleDbParameter("#DatPrepa", DTPechprep.Value)) 'adding date parameters to datatable
da.SelectCommand.Parameters.Add(New OleDbParameter("#datau", DTPechprep.Value)) 'adding date parameters to datatable
'da.SelectCommand.Parameters.Add(New OleDbParameter("#Matrice", matrice.ToString)) 'adding Matrice parameters to datatable
da.Fill(MyDataSet, "Matrice")
DataGridView1.DataSource = MyDataSet.Tables("Matrice")
'to focus on first row of DGV after populating it
DataGridView1.Rows(0).Selected = True
LBnumresult.Text = DataGridView1.RowCount - 1

Update query makes the fields empty in the database

I asked a question previously concerning updating data in a datagridview with phpMyAdmin. You can refer to it by following link -->Updating data in phpmyadmin part 1
The code works quite OK, but now the problem is that when I check for the updated data in localhost all I see are empty fields. Below is the screenshot of my vb in design. I have labelled the textboxes as per my database. The textboxes in the screenshot are set to be invisible on running my winform.
What exactly could be the problem?
#Kakarot
Here is what I initially had
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=server;password=server;database=heavisa_database"
Dim rabit As MySqlDataReader
MysqlConn.Open()
Dim pin As String
pin = "UPDATE heavisa_database.new_employee SET (Employee_ID = '" & txtemployeeid.Text & "', Nat_ID = '" & txtnatid.Text & "', First_Name = '" & txtfirstname.Text & "', Middle_Name = '" & txtmiddlename.Text & "', Surname = '" & txtsurname.Text & "', NSSF_No = '" & txtnssfno.Text & "', KRA_Pin = '" & txtkrapin.Text & "', NHIF_No = '" & txtnhifno.Text & "', Residence = '" & txtresidence.Text & "', Mobile_No = '" & txtmobileno.Text & "', Email = '" & txtemail.Text & "', Job_Group = '" & cbojobgroup.Text & "', Employment_Date = '" & dtpemploymentdate.Text & "') WHERE Employee_ID = '" & txtemployeeid1.Text & "'"
Try
con = New MySqlCommand(pin, MysqlConn)
rabit = con.ExecuteReader
MessageBox.Show("Update Successful.")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
And here is what I currently have (credit goes to one Mr. ekad for it)
Dim pin As String
pin = "UPDATE heavisa_database.new_employee SET Employee_ID = #Employee_ID, Nat_ID = #Nat_ID, First_Name = #First_Name, Middle_Name = #Middle_Name, Surname = #Surname, NSSF_No = #NSSF_No, KRA_Pin = #KRA_Pin, NHIF_No = #NHIF_No, Residence = #Residence, Mobile_No = #Mobile_No, Email = #Email, Job_Group = #Job_Group, Employment_Date = #Employment_Date WHERE Employee_ID like '%{0}%'"
Try
Using MysqlConn As New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=server;password=server;database=heavisa_database"
MysqlConn.Open()
Using con As New MySqlCommand(pin, MysqlConn)
With con
con.Parameters.AddWithValue("#Employee_ID", txtemployeeid.Text)
con.Parameters.AddWithValue("#Nat_ID", txtnatid.Text)
con.Parameters.AddWithValue("#First_Name", txtfirstname.Text)
con.Parameters.AddWithValue("#Middle_Name", txtmiddlename.Text)
con.Parameters.AddWithValue("#Surname", txtsurname.Text)
con.Parameters.AddWithValue("#NSSF_No", txtnssfno.Text)
con.Parameters.AddWithValue("#KRA_Pin", txtkrapin.Text)
con.Parameters.AddWithValue("#NHIF_No", txtnhifno.Text)
con.Parameters.AddWithValue("#Residence", txtresidence.Text)
con.Parameters.AddWithValue("#Mobile_No", txtmobileno.Text)
con.Parameters.AddWithValue("#Email", txtemail.Text)
con.Parameters.AddWithValue("#Job_Group", cbojobgroup.Text)
con.Parameters.AddWithValue("#Employment_Date", dtpemploymentdate.Text)
End With
con.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Update Successful.")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
The first code gave me an error (refer to the link above). The second code works but it's emptying my fields instead of updating.
How did you updated your tables in your database? It should be like:
(Im gonna take my code for an old project that I did)
Private Sub disconnect()
conn.Close()
End Sub
Private Sub connect()
conn.ConnectionString = connectionString
conn.Open()
End Sub
Private Sub btnSaveEdit_Click(sender As Object, e As EventArgs) Handles btnSaveEdit.Click
connect()
Dim query as string
Dim command As New MySqlCommand
query = "Update `tblcandidates` set firstname = '" & txtEditFname.Text & "', lastname = '" & txtEditLName.Text & "', position='" & cboEditPosition.Text & "', fullname = '" & fullname & "' where recNum = '" & txtRec.Text & "'"
command.Connection = conn
command.CommandText = query
command.ExecuteNonQuery()
disconnect()
End Sub
First things first, just a simple question, is heavisa_database.new_employee a table? It's really wise to properly name them, you can put tbl before your desired name if its a table, and db before the name if its a database. Just to prevents confusions. And I think you dont need a reader when updating records in your table, correct me if I'm wrong :p
Okay, to be honest, I don't really understand much the code that Mr. ekad provided. Here's a code you can try. And oh, you don't really need the bracket after the SET.
//Global Vars
Dim connectionString As String = "server=localhost;userid=server;password=server;database=heavisa_database"
Dim conn As New MySqlConnection
First, let's make some functions for ease (you can put this anywhere in your code):
//remember that conn is our MySqlConnection
Private Sub connect()
conn.ConnectionString = connectionString
conn.Open()
End Sub
Private Sub disconnect()
conn.Close()
End Sub
So, event for your update button:
connect()
Dim pin As String
pin = "UPDATE new_employee SET Employee_ID = '" & txtemployeeid.Text & "', Nat_ID = '" & txtnatid.Text & "', First_Name = '" & txtfirstname.Text & "', Middle_Name = '" & txtmiddlename.Text & "', Surname = '" & txtsurname.Text & "', NSSF_No = '" & txtnssfno.Text & "', KRA_Pin = '" & txtkrapin.Text & "', NHIF_No = '" & txtnhifno.Text & "', Residence = '" & txtresidence.Text & "', Mobile_No = '" & txtmobileno.Text & "', Email = '" & txtemail.Text & "', Job_Group = '" & cbojobgroup.Text & "', Employment_Date = '" & dtpemploymentdate.Text & "' WHERE Employee_ID = '" & txtemployeeid1.Text & "'"
//lets create new command
Dim command As New MySqlCommand
//sets the connection for our command
command.Connection = conn
command.CommandText = pin
command.ExecuteNonQuery()
disconnect()
MessageBox.Show("Record saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
Try the given code above and I'm pretty sure It'll work. Goodluck!

no value given for one or more required parameters in updating deleting records

I cant figure out whats wrong with this,when i update a record from my list view a pop up appears saying no value given for one or more required parameters.
heres my code:
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles BtnUpdate.Click
Try
Dim SqlQuery As String = "UPDATE UsersTable Set AccountType = '" & CmbAccountType.Text & "' , Username = '" & TxtUsername.Text & "' , UserPassword = '" & TxtPassword.Text & "' , Firstname = '" & TxtFirstname.Text & "' , Lastname = '" & TxtLastname.Text & "' , Sex = '" & CmbSex.Text & "',Birthdate = '" & DateTimePickerBirthdate.Text & "' , ContactNumber = '" & TxtContact.Text & "' , Address = '" & TxtAddress.Text & "' WHERE UserID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = Conn
.ExecuteNonQuery()
End With
MsgBox("Account successfully updated!")
loadlistview()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles BtnDelete.Click
Try
Dim SqlQuery As String = "DELETE FROM ProductTable WHERE UserID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = Conn
.ExecuteNonQuery()
End With
MsgBox("Account deleted.")
loadlistview()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
The problem is in the WHERE condition which you used in your query. so you can correct it by using the following query
In update query :
Dim SqlQuery As String = "UPDATE UsersTable Set AccountType = '" & CmbAccountType.Text & "'....................." & _
"WHERE UserID = '" & id & "';" '<----- you miss a single quote in where clause.
In Delete query :
Dim SqlQuery As String = "DELETE FROM ProductTable WHERE UserID = '" & id & "';"