vb.net mySql Datagridview refresh problems - mysql

Recently i was trying to display data on datagridview but every time there is a new entry the DGV (datagridview) was not refreshing. I made a new method called showtable but when i search i use to get the database names insted of moded names in the code for example tax to TAX and so on..
This is the code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
konekcija = New MySqlConnection
konekcija.ConnectionString =
"server=localhost;userid=root;password=root;database=baza"
Dim READER As MySqlDataReader
Try
Dim kupovnacena As Double
Dim prodaznacena As Double
kupovnacena = TextBoxKupovna.Text
prodaznacena = TextBoxProdazna.Text
If kupovnacena > prodaznacena Then
MessageBox.Show("Продажната цена не може да биде помала од куповната !")
TextBoxKupovna.Text = ""
TextBoxProdazna.Text = ""
End If
konekcija.Open()
If TextBoxBarkod.Text = "" Then
MessageBox.Show("Внеси баркод/шифра")
End If
If TextBoxNaziv.Text = "" Then
MessageBox.Show("Внеси назив на артиклот")
End If
If TextBoxKupovna.Text = "" Then
MessageBox.Show("Внеси куповна цена на артиклот")
End If
If TextBoxProdazna.Text = "" Then
MessageBox.Show("Внеси продажна цена на артиклот")
TextBoxProdazna.Text = Focus()
End If
Dim Query As String
Query = "insert into baza.artikli(id,barkod,naziv,kupovna,prodazna,opis,kolicina,proizvoditel,ddv,makpr) values ('" & TextBoxID.Text & "','" & TextBoxBarkod.Text & "','" & TextBoxNaziv.Text & "','" & TextBoxKupovna.Text & "','" & TextBoxProdazna.Text & "','" & TextBoxOpis.Text & "','" & TextBoxKolicina.Text & "','" & TextBoxProiz.Text & "','" & ddv & "','" & makpr & "')"
COMMAND = New MySqlCommand(Query, konekcija)
READER = COMMAND.ExecuteReader
MessageBox.Show("Артиклот е успешно ажуриран !")
TextBoxBarkod.Text = ""
TextBoxKupovna.Text = ""
TextBoxNaziv.Text = ""
TextBoxOpis.Text = ""
TextBoxProdazna.Text = ""
TextBoxKolicina.Text = ""
TextBoxID.Text = ""
TextBoxProiz.Text = ""
konekcija.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
konekcija.Dispose()
datagridview1.refresh()
End Try
End Sub

Related

How do i fix an error for an unhandled exception?

I'm getting this error when I click the update button in my form:
" An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'intGenderID'."
The update does not work.
Could anyone point me in the right direction? Thanks in advance!
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim strSelect As String = ""
Dim strFirstName As String = ""
Dim strLastName As String = ""
Dim strAddress As String = ""
Dim strCity As String = ""
Dim strState As String = ""
Dim strZip As String = ""
Dim strPhoneNumber As String = ""
Dim strEmail As String = ""
Dim intRowsAffected As Integer
Dim cmdUpdate As OleDb.OleDbCommand
If Validation() = True Then
' open database
If OpenDatabaseConnectionSQLServer() = False Then
' No, warn the user ...
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
If Validation() = True Then
strFirstName = txtFirstName.Text
strLastName = txtLastName.Text
strAddress = txtAddress.Text
strCity = txtCity.Text
strState = txtState.Text
strZip = txtZip.Text
strPhoneNumber = txtPhoneNumber.Text
strEmail = txtEmail.Text
strSelect = "Update TGolfers Set strFirstName = '" & strFirstName & "', " & "strLastName = '" & strLastName &
"', " & "strAddress = '" & strAddress & "', " & "strCity = '" & strCity & "', " &
"strState = '" & strState & "', " & "strZip = '" & strZip & "', " &
"strPhoneNumber = '" & strPhoneNumber & "', " & "strEmail = '" & strEmail & "', " &
"intShirtSizeID = '" & cboShirtSizes.SelectedValue.ToString & "' " &
"intGenderID = '" & cboGenders.SelectedValue.ToString & "' " &
"Where intGolferID = " & cboGolfers.SelectedValue.ToString
MessageBox.Show(strSelect)
cmdUpdate = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
intRowsAffected = cmdUpdate.ExecuteNonQuery()
If intRowsAffected = 1 Then
MessageBox.Show("Update successful")
Else
MessageBox.Show("Update failed")
End If
CloseDatabaseConnection()
frmManageGolfers_Load(sender, e)
End If
End If
End Sub
Syntax error means that the SQL isn't the right syntax. Its quite strict.
Near 'intGenderID' means the syntax error is just before this. In your case, you've missed a comma.
I will proceed as if this MySql. Keep your database objects local. You need to keep track that they are closed and disposed. `Using...End Using blocks take care of this even if there is an error.
Always use parameters. Not only does it make writing the sql statement much easier it will save your database from sql injection.
Additional comments in-line.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim intRowsAffected As Integer
Dim strSelect As String = "Update TGolfers Set strFirstName = #FirstName, strLastName = #LastName, strAddress = #Address, strCity = #City, strState = #State, strZip = #Zip, strPhoneNumber = #Phone, strEmail = #EMail, intShirtSizeID = #ShirtSize, intGenderID = #Gender Where intGolferID = #GolferID;"
If Not Validation() Then
'Actually the input should be validated before we get here
MessageBox.Show("Did not pass validation. Correct the input")
Return
End If
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(strSelect, cn)
cmd.Parameters.Add("#FirstName", MySqlDbType.VarChar).Value = txtFirstName.Text
cmd.Parameters.Add("#LastName", MySqlDbType.VarChar).Value = txtLastName.Text
cmd.Parameters.Add("#Address", MySqlDbType.VarChar).Value = txtAddress.Text
cmd.Parameters.Add("#City", MySqlDbType.VarChar).Value = txtCity.Text
cmd.Parameters.Add("#State", MySqlDbType.VarChar).Value = txtState.Text
cmd.Parameters.Add("#Zip", MySqlDbType.VarChar).Value = txtZip.Text
cmd.Parameters.Add("#Phone", MySqlDbType.VarChar).Value = txtPhoneNumber.Text
cmd.Parameters.Add("#EMail", MySqlDbType.VarChar).Value = txtEmail.Text
'Are you sure you have set the .ValueMember of the combo boxes?
cmd.Parameters.Add("#ShirtSize", MySqlDbType.VarChar).Value = cboShirtSizes.SelectedValue.ToString
cmd.Parameters.Add("#Gender", MySqlDbType.VarChar).Value = cboGenders.SelectedValue.ToString
'Are your sure that intGolferID is not a number
cmd.Parameters.Add("#GolferID", MySqlDbType.Int32).Value = cboGolfers.SelectedValue
cn.Open()
intRowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
If intRowsAffected = 1 Then
MessageBox.Show("Update successful")
Else
MessageBox.Show("Update failed")
End If
frmManageGolfers.Show() 'I can't image why you would try to send a button and the button's event args to the Load event of another form
End Sub

vb.net data connection with mysql

Recently i build a pos but the datagridview doesnt refresh i tried different methods but its not worikng
Dim Query As String
Query = "insert into bazaartikli123.artikli(id,barkod,naziv,kupovna,prodazna,opis) values ('" & TextBoxBarkod.Text & "','" & TextBoxNaziv.Text & "','" & TextBoxKupovna.Text & "','" & TextBoxProdazna.Text & "','" & TextBoxOpis.Text & "')"
COMMAND = New MySqlCommand(Query, konecija)
READER = COMMAND.ExecuteReader
Dim dataadapter As New SqlDataAdapter(sql, konekcija)
Dim ds As New DataSet()
MessageBox.Show("Артиклот е успешно внесен !")
TextBoxBarkod.Text = ""
TextBoxKupovna.Text = ""
TextBoxNaziv.Text = ""
TextBoxOpis.Text = ""
TextBoxProdazna.Text = ""
dataadapter.Fill(ds)
konecija.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Artikli"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
konecija.Dispose()
End Try
Bazadataset ,ArtikliBindingSource , ArtikliTableAdapter

DataGridView select multiple row, check each row

I am trying to select all rows by a button or select different rows with ctrl+click.
But even if I have selected multiple rows, it only checks the first row. Then it rereads it again instead of going to the next row.
I'm not sure either where to put the multiselect code.
Originally, you're only supposed to just click a row then check if conditions are satisfied. However it was requested that you can do multiple and check each row if condition is satisfied.
Here is my code:
Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
Dim i As Integer
i = DataGridView1.CurrentRow.Index
_subjectno = DataGridView1.Item(0, i).Value
_title = DataGridView1.Item(1, i).Value
_unit = DataGridView1.Item(2, i).Value
_pre = DataGridView1.Item(3, i).Value
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
DataGridView1.MultiSelect = True
DataGridView1.SelectAll()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim selectedItems As DataGridViewSelectedRowCollection = DataGridView1.SelectedRows
For Each selectedItem As DataGridViewRow In selectedItems
add()
Next
End Sub
Sub add()
Try
If IS_EMPTY(txtSno) = True Then Return
cm = New MySqlCommand("select * from tblenroll where subjectnumber like '" & _subjectno & "' and remarks <> 'Failed' and studentno like '" & txtSno.Text & "'", cn)
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
MsgBox("Subject is already taken.", vbExclamation)
dr.Close()
Return
Else
dr.Close()
End If
If _pre = "NONE" Or _pre = "2ND YR STANDING" Or _pre = "3RD YR STANDING" Or _pre = "4TH YR STANDING" Or _pre = "5TH YR STANDING" Then
cm = New MySqlCommand("insert into tblenroll (studentno, subjectnumber, ay,semester,dateenrolled, curriculum) values ('" & txtSno.Text & "','" & _subjectno & "','" & txtAY.Text & "','" & txtSem.Text & "','" & Now & "','" & txtCurriculum.Text & "')", cn)
cm.ExecuteNonQuery()
MsgBox(_subjectno & " successfully added.", vbInformation)
LoadEnrolled()
Else
cm = New MySqlCommand("select * from tblenroll where studentno like '" & txtSno.Text & "' and subjectnumber like '" & _subjectno & "' and ay like '" & txtAY.Text & "'", cn)
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
MsgBox("Subject is already taken.", vbExclamation)
dr.Close()
Return
Else
dr.Close()
End If
Dim strok As Boolean = False
Dim strArr() As String
Dim count As Integer
Dim strpre As String = _pre
strArr = strpre.Split(", ")
For count = 0 To strArr.Length - 1
cm = New MySqlCommand("select * from tblenroll as e inner join tblsubject as s on e.subjectnumber = s.subjectno where s.subjectno like '%" & Trim(strArr(count)) & "%' and studentno like '" & txtSno.Text & "' and remarks like 'Passed'", cn)
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
dr.Close()
strok = True
Else
MsgBox("Unable to enroll this subject. Pre-requisite " & strArr(count) & ".", vbExclamation)
dr.Close()
Return
End If
Next
If strok = True Then
cm = New MySqlCommand("insert into tblenroll (studentno, subjectnumber, ay, semester, dateenrolled, curriculum) values ('" & txtSno.Text & "','" & _subjectno & "','" & txtAY.Text & "','" & txtSem.Text & "','" & Now & "','" & txtCurriculum.Text & "')", cn)
cm.ExecuteNonQuery()
MsgBox(_subjectno & " successfully added.", vbInformation)
LoadEnrolled()
End If
End If
Catch ex As Exception
MsgBox(ex.Message, vbCritical)
End Try
End Sub
Thank you so much!
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
For Each selectedItem As DataGridViewRow In DataGridView1.SelectedRows
_subjectno = selectedItem.Cells(0).Value
_title = selectedItem.Cells(1).Value
_unit = selectedItem.Cells(2).Value
_pre = selectedItem.Cells(3).Value
add()
Next
End Sub

Cannot update a textbox on a form in Access vba

I am working on an Access DB that sorts and tracks my firm's business contacts. We have a form called "Contact Profile" whereby the user can select a given contact and view all of his information: First Name, Last Name, Company, Title, Email Address, etc.
On the profile, the user can update a contact's information with the "Update Info" button.
Every single field updates just fine--with the exception of Email Address. For example, I can change Joseph Smith, Programmer at Google to Joe Smith, Program Manager at GOOG with no issues.
But if I try to change joesmith#google.com to jsmith#google.com, the change does not save. Code is posted below. Could someone please take a look and let me know if they have any suggestions? Thanks!
Private Sub Command61_Click()
Dim strFirstName As String
Dim strLastName As String
Dim strIndustry As String
Dim strCountry As String
Dim strState As String
Dim strCity As String
Dim strCompany As String
Dim strTitle As String
Dim strStatus As String
Dim strPhone As String
Dim strEmail As String
Dim strOwner As String
Dim DateNow As String
'Allow user to leave some fields blank. User must fill in certain fields.
Dim VisEnable
If IsNull(Me.txtFirstName) Then
MsgBox ("Please add First Name for this Prospect")
Me.txtFirstName.SetFocus
Exit Sub
End If
If IsNull(Me.txtLastName) Then
MsgBox ("Please add Last Name for this Prospect")
Me.txtLastName.SetFocus
Exit Sub
End If
If IsNull(Me.cboIndustry) Then
Me.cboIndustry = ""
End If
If IsNull(Me.cboGeo) Then
Me.cboGeo = ""
End If
If IsNull(Me.cboInfluence) Then
Me.cboInfluence = ""
End If
If IsNull(Me.cboSchool) Then
Me.cboSchool = ""
End If
If IsNull(Me.cboTier) Then
Me.cboTier = ""
End If
If IsNull(Me.cboCompany) Then
Me.cboCompany = ""
End If
If IsNull(Me.txtTitle) Then
Me.txtTitle = ""
End If
If IsNull(Me.cboStatus) Then
Me.cboStatus = ""
End If
If IsNull(Me.cboOwner) Then
Me.cboOwner = ""
End If
If IsNull(Me.txtPhone) Then
Me.txtPhone = ""
End If
If IsNull(Me.txtEmail) Then
MsgBox ("Please add Email for this Prospect")
Me.txtEmail.SetFocus
Exit Sub
End If
If IsNull(Me.txtNotes) Then
Me.txtNotes = ""
End If
If IsNull(Me.txtInitialProspectEmailSentDate) Then
Me.txtInitialProspectEmailSentDate = ""
End If
If IsNull(Me.txtNextTouchPoint) Then
Me.txtNextTouchPoint = ""
End If
strFirstName = Me.txtFirstName
strLastName = Me.txtLastName
strIndustry = Me.cboIndustry
strCompany = Me.cboCompany
strTitle = Me.txtTitle
strStatus = Me.cboStatus
strPhone = Me.txtPhone
strEmail = Me.txtEmail
strNotes = Me.txtNotes
strOwner = Me.cboOwner
dtEmailSent = Me.txtInitialProspectEmailSentDate
dtNextTouchPoint = Me.txtNextTouchPoint
strRegion = Me.cboGeo
strSoR = Me.cboTier
strInfluence = Me.cboInfluence
strClient = Me.ckClient
strCoworker = Me.ckCoworker
strSchool = Me.cboSchool
strSQL = "Update tblProspect Set FirstName = " & """" & strFirstName & """" & ",LastName = " & """" & strLastName & """" & ",Industry = " & """" & strIndustry & """" & "" & _
",Geography = " & """" & strRegion & """" & ",StrengthofRelationship = " & """" & strSoR & """" & ",School = " & """" & strSchool & """" & ",Company = " & """" & strCompany & """" & "" & _
",Title = " & """" & strTitle & """" & ",Status = " & """" & strStatus & """" & ", InfluenceLevel = " & """" & strInfluence & """" & ", FormerClient = " & strClient & ", FormerCoWorker = " & strCoworker & "" & _
",Email = " & """" & strEmail & """" & ",Phone = " & """" & strPhone & """" & ",ProspectOwner = " & """" & strOwner & """" & ",Notes = " & """" & strNotes & """" & ""
If dtNextTouchPoint <> "" Then
strSQL = strSQL & " ,NextTouchPoint = #" & dtNextTouchPoint & "#"
End If
If dtEmailSent <> "" Then
strSQL = strSQL & " ,LastEmailDate = #" & dtEmailSent & "#"
End If
strSQL = strSQL & " WHERE Email = " & """" & strEmail & """" & ""
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
Dim ctl As Control
For Each ctl In Me.Controls
Select Case ctl.ControlType
Case acTextBox, acComboBox, acListBox, acCheckBox
If ctl.ControlSource = "" Then
ctl.Value = Null
End If
Case Else
End Select
Next ctl
Me.Visible = False
DoCmd.OpenForm "frmProspectAdmin", acNormal, , , acFormEdit, acWindowNormal
DoCmd.RunCommand acCmdSaveRecord
Form_frmProspectProfile.Refresh
Form_frmProspectAdmin.Refresh
End Sub
It comes out exactly likely I want it to in Debug.Print, but it does not save that way in the contact profile.
Debug.Print strSQL
Update tblProspect Set FirstName = "Jon",LastName = "Snow",Industry = "Other",Geography = "",StrengthofRelationship = "",School = "",Company = "",Title = "",Status = "Dead", InfluenceLevel = "", FormerClient = 0, FormerCoWorker = 0,Email = "jsnow#winterfell",Phone = "",ProspectOwner = "",Notes = ""

error database: Syntax error in INSERT INTO statement

I'm having difficulties with my library system. I get an error that states "error database: Syntax error in INSERT INTO statement". I'm using Access for the data base.
Here's my code:
Public Class Form7
Private Sub Form7_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
Me.Text = "Registration"
sqlCon.Close()
sqlCon.Close()
clear()
End Sub
Private Sub Form7_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Split(Me.Text, " - ")(1) = "Edit" Then
sqlSTR = "Select * From BookRegister WHERE id = " & globalID
ExecuteSQLQuery(sqlSTR)
If sqlDr.Read Then
TextBox1.Text = sqlDr(1)
TextBox2.Text = sqlDr(2)
TextBox3.Text = sqlDr(3)
TextBox4.Text = sqlDr(4)
TextBox5.Text = sqlDr(5)
TextBox6.Text = sqlDr(6)
TextBox7.Text = sqlDr(7)
TextBox7.Text = sqlDr(8)
End If
End If
End Sub
Private Sub TextBox6_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox6.TextChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf TextBox2.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf TextBox3.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox4.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox5.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox6.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox7.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf TextBox8.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf Split(Me.Text, " - ")(1) = "Add" Then
sqlSTR = "INSERT INTO BookRegister(ISBN, Title, Author, Volume, Pages, Publisher, Section, Year_Published) " & _
"VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "'" & _
",'" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & ")"""
ExecuteSQLQuery(sqlSTR)
MsgBox("New record has been saved.", MsgBoxStyle.Information)
clear()
Else
sqlSTR = "UPDATE BookRegister SET ISBN ='" & TextBox1.Text & "', " & _
"title='" & TextBox2.Text & "', " & _
"author='" & TextBox3.Text & "', " & _
"volume='" & TextBox4.Text & "', " & _
"pages='" & TextBox5.Text & "', " & _
"publisher='" & TextBox6.Text & "', " & _
"section='" & TextBox7.Text & "', " & _
"year_published='" & Format("yyyy", TextBox8.Text) & "', " & _
" WHERE id =" & globalID
ExecuteSQLQuery(sqlSTR)
MsgBox("Record has been updated !!", MsgBoxStyle.Information)
clear()
globalID = 0
edit = False
Me.Close()
End If
FillListView(Form6.ListView1, ExecuteSQLQuery("select * from bookregister"))
End Sub
Private Sub clear()
Textbox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
It looks like you are missing a final single quote at the end of your INSERT statement, and then appending an extraneous double quote after the closing parenthesis, i.e.,
& "','" & TextBox8.Text & ")"""
should be
& "','" & TextBox8.Text & "')"