I'm using MySQL in vb.net
Datagridview displayed correctly and everything works properly, the problem arises when I try to update the changes in the database with the update (method)
By default the data is updated in memory "is erased students with ID =" 2 ""
But in the database is not updated, I'm reading the documentation and should work with update
datosAlumnos.Update(ds, "alumnos")
Imports MySql.Data.MySqlClient
Public Class Form1
Dim con As New MySqlConnection
Dim stringCon As String = "server=localhost; user id=root; password=; database=centroeducativo"
Dim listViewAlumnos As New ListBox()
Dim ds As New DataSet()
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Try
con.ConnectionString = stringCon
con.Open()
Dim datosTablas As New MySqlDataAdapter("SHOW TABLES", con)
Dim datosAlumnos As New MySqlDataAdapter("SELECT * FROM alumnos ORDER BY Nombre", con)
Dim datosAsignaturas As New MySqlDataAdapter("SELECT * FROM asignaturas", con)
Dim datosMatriculas As New MySqlDataAdapter("SELECT * FROM matriculas", con)
datosTablas.Fill(ds, "tablas")
datosAlumnos.Fill(ds, "alumnos")
datosAsignaturas.Fill(ds, "asignaturas")
datosMatriculas.Fill(ds, "matriculas")
con.Close()
Dim tabla As DataTable
tabla = ds.Tables("tablas")
Dim fila As DataRow
Me.ListBox1.Items.Clear()
For Each fila In tabla.Rows
Me.ListBox1.Items.Add(fila.Item("Tables_in_centroeducativo"))
Next
Dim filaBorrada As DataRow() = ds.Tables("alumnos").Select("id=2")
filaBorrada(0).Delete()
datosAlumnos.Update(ds, "alumnos")
Catch ex As Exception
End Try
End Sub
Private Sub formularioTabla(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim curItem As String = ListBox1.SelectedItem.ToString()
Select Case curItem
Case "alumnos"
FormularioAlumno()
Case "asignaturas"
FormularioAsignaturas()
Case "matriculas"
FormularioMatriculas()
Case Else
MsgBox("none")
End Select
End Sub
Private Sub FormularioAlumno()
Panel1.Controls.Clear()
Dim dv As DataView = ds.Tables("alumnos").DefaultView
con.Close()
Dim DataGridView As New DataGridView()
Panel1.Controls.Add(DataGridView)
DataGridView.AutoSize = True
DataGridView.DataSource = dv
DataGridView.Columns("id").Visible = False
End Sub
End Class
It seems you forget to set InsertCommand, UpdateCommand and specially Deletecommand.
To make a data adapter update data, it should have those commands. You can set those commands manually or using a MySqlCommandBuilder.
Dim myConn As New MySqlConnection("Connection String")
Dim myDataAdapter As New MySqlDataAdapter()
myDataAdapter.SelectCommand = New MySqlCommand("Select Query", myConn)
Dim myCommandBuilder As MySqlCommandBuilder = New MySqlCommandBuilder(myDataAdapter)
Related
I need to show a set of data from MySQL like the function of DataGridView or ListView, but using multiple TextBox controls. The result of my work is that all data from a column is together on one TextBox. I don't know how to make a loop.
Code:
Imports System.Data
Imports MySql.Data.MySqlClient
Public Class Form1
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Dim query As String = "SELECT id,timein,timeout FROM emp"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using myCommand As New MySqlCommand("SELECT * FROM emp ORDER BY id ASC", con)
Try
con.Open()
Using myData = myCommand.ExecuteReader()
If myData.HasRows Then
While myData.Read()
Dim idline = String.Format("{0}", myData.GetString(myData.GetOrdinal("id")), Environment.NewLine)
Dim inline = String.Format("{0}", myData.GetString(myData.GetOrdinal("timein")), Environment.NewLine)
Dim outline = String.Format("{0}", myData.GetString(myData.GetOrdinal("timeout")), Environment.NewLine)
idbox1.Text &= idline
idbox2.Text &= idline
idbox3.Text &= idline
timein1.Text &= inline
timein2.Text &= inline
timein3.Text &= inline
timeout1.Text &= inline
timeout2.Text &= inline
timeout3.Text &= inline
End While
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Using
con.Close()
End Sub
End Class
This works fine with me. I got what I need to do. Thank you for the ideas.
"Imports System.Data
Imports MySql.Data.MySqlClient
Public Class Form2
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Dim query As String = "SELECT id,timein,timeout FROM emp"
con.Open()
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM emp ORDER BY id ASC", con)
da.Fill(dt)
idbox1.Text = dt.Rows(0)("id").ToString()
idbox2.Text = dt.Rows(1)("id").ToString()
idbox3.Text = dt.Rows(2)("id").ToString()
timein1.Text = dt.Rows(0)("timein").ToString()
timein2.Text = dt.Rows(1)("timein").ToString()
timein3.Text = dt.Rows(2)("timein").ToString()
timeout1.Text = dt.Rows(0)("timeout").ToString()
timeout2.Text = dt.Rows(1)("timeout").ToString()
timeout3.Text = dt.Rows(2)("timeout").ToString()
con.Close()
End Sub
End Class
"
Have you tried using a DataTable? I built a form that pulls values on load from into a DataTable and in that table you can specify the columns that appear and in what order. I used the built in functions in MS VS17 RC to link the tables. Might help you out with your issue.
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sqlConn As New SqlConnection("Connection String Info")
Dim cmd As New SqlCommand
Dim dr As New SqlDataAdapter("-Query String-", sqlConn)
Dim dt As New DataTable
Try
If sqlConn.State = ConnectionState.Closed Then
sqlConn.Open()
dr.Fill(dt)
Menu.DisplayMember = "prod_name" --add your columns here
Menu.DataSource = dt
sqlConn.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Order.Clear()
For Each Item As Object In Menu.SelectedItems
Order.AppendText(Item.ToString = Environment.NewLine)
Next
End Sub
I was following a tutorial on the internet ( link ) to create a a picture gallery. I got it all working, but i changed:
Private Sub CreateGallery()
i = 0
RemoveControls()
If Directorypath IsNot Nothing Then
Dim di As New IO.DirectoryInfo(Directorypath)
Dim diar1 As IO.FileInfo() = di.GetFiles("*.jpg").Concat(di.GetFiles("*.bmp")).Concat(di.GetFiles("*.png")).Concat(di.GetFiles("*.gif")).ToArray
Dim dra As IO.FileInfo
For Each dra In diar1
DrawPictureBox(dra.FullName, dra.Name)
Next
End If
End Sub
to:
Private Sub CreateGallery()
Dim table = New DataTable
Using Connection = New MySqlConnection("Server=localhost;User Id=root;Password=barra;Database=pap")
Using da = New MySqlDataAdapter("SELECT * FROM filme", Connection)
da.Fill(table)
End Using
End Using
i = 0
RemoveControls()
For Each row As DataRow In table.Rows
Try
Dim bytes() As Byte
bytes = (row("imagem"))
Dim memStream As New MemoryStream(bytes)
DrawPictureBox(memStream, row("titulo"))
Catch ex As Exception
End Try
Next
End Sub
It was working fine, the way i wanted, when i tried to do it on another project it gives me an error on 'MySqlDataAdapter':
Using da = New MySqlDataAdapter("SELECT * FROM filme", Connection)
the erros says : Overload resolution failed because no accessible 'New' can be called with these arguments
I tried almost everything i can't make it work.
convert your function as class and call :
dim new_creator as yourclass
...
Try This
Private Sub CreateGallery()
Dim table As New DataTable
Dim Conn As New SqlConnection
Conn = New SqlConnection("Initial Catalog=<DataBase>;User ID=sa;password=<password>;Data Source=<ServerName>"")
Dim com As String = ""
com = "SELECT * FROM Table "
Dim getComm As New SqlDataAdapter(com, Conn)
getComm.Fill(table)
i = 0
RemoveControls()
For Each row As DataRow In table.Rows
Dim bytes() As Byte
bytes = (row("Imagee"))
Dim memStream As New MemoryStream(bytes)
DrawPictureBox(memStream, row("Bro_Path"))
End Sub
and change ByVal _filename As MemoryStream,
Private Sub DrawPictureBox(ByVal _filename As MemoryStream, ByVal _displayname As String)
When my form for creating a group of students loads up, I receive a NullReferenceException for seemingly no reason. This is the code that handles the form loading:
Private Sub AddGroupForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To Form1.lstStudents.Items.Count - 1
lstStudentList.Items.Add(Form1.lstStudents.Items.Item(i))
Next
tempStudentList.AddRange(Form1.mainStudentList)
btnAllOut.Enabled = False
btnOneOut.Enabled = False
End Sub
The mainStudentList referred to is a list that is populated upon loading by using MySQL:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim conn As New MySqlConnection("server=localhost;user=root;database=new_project;port=3306;password=********;")
conn.Open()
Dim command As New MySqlCommand("SELECT * FROM students WHERE deleted=0 ORDER BY lastName;", conn)
Dim dataSet As New DataSet()
Dim dataAdapter As New MySqlDataAdapter()
dataAdapter.SelectCommand = command
dataAdapter.Fill(dataSet, "students")
Dim dataTable As DataTable = dataSet.Tables("students")
For Each row As DataRow In dataTable.Rows
Dim newStudent As New Student
newStudent.intIDNum = row.Item("passCode")
newStudent.strFirstName = row.Item("firstName")
newStudent.strLastName = row.Item("lastName")
newStudent.chrGender = row.Item("gender")
newStudent.dateDOB = row.Item("dateOfBirth")
newStudent.intAge = CInt(Today.Year - newStudent.dateDOB.Year)
newStudent.intYearGroup = row.Item("yearGroup")
newStudent.intSkillLevel = SByte.Parse(row.Item("skillLevel"))
mainStudentList.Add(newStudent)
lstStudents.Items.Add(newStudent.nameConcat(newStudent.strFirstName, newStudent.strLastName))
Next
conn.Close()
Catch ex As Exception
MsgBox("Error: " & ex.ToString())
End Try
End Sub
The specific exception occurs when the tempStudentList attempts to load the values in the mainStudentList. Specifically, it states that "Object reference not set to instance of an Object".
Make sure mainStudentList has been initialized first.
c#
List<Student> mainStudentList = new List<Student>();
VB.Net
Dim mainStudentList As New List(Of Student)()
when i click the button 2 with the valid ID No. on the text box it always shows the message box "Invalid ID No." but if i remove the IF statement, it shows database records and it works fine, but i need this IF statement, i think the problem here is the dr.HasRows but i don't know what to put.
Imports MySql.Data.MySqlClient
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;database=db")
Dim DataSet1 As New DataSet
Dim dr As MySqlDataReader
Dim da As New MySqlDataAdapter
Dim cmd As New MySqlCommand
con.ConnectionString = "server = localhost; user id = root;password=root; database = db"
cmd.Connection = con
con.Open()
cmd.CommandText = "select * from voter where idn='" & TextBox1.Text & "'"
dr = cmd.ExecuteReader
con.Close()
da.SelectCommand = cmd
da.Fill(DataSet1, "db")
If dr.HasRows Then
Label2.DataBindings.Add("text", DataSet1, "db.fname")
Label10.DataBindings.Add("text", DataSet1, "db.mi")
Label11.DataBindings.Add("text", DataSet1, "db.lname")
Label12.DataBindings.Add("text", DataSet1, "db.yr")
Label13.DataBindings.Add("text", DataSet1, "db.sec")
Label14.DataBindings.Add("text", DataSet1, "db.vstatus")
Else
MessageBox.Show("Invalid ID No.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Label2.DataBindings.Clear()
Label10.DataBindings.Clear()
Label11.DataBindings.Clear()
Label12.DataBindings.Clear()
Label13.DataBindings.Clear()
Label14.DataBindings.Clear()
End Sub
End Class
You need to use Parameterized query to prevent SQL Injection
Dim commandText as String = "SELECT * FROM Voter WHERE idn=#idn"
Dim command As New MySqlCommand(commandText, connection)
command.Parameters.AddWithValue("#idn", TextBox1.Text)
You don't need to use DataSet and DataAdapter if you are using a DataReader because you could convert your DataReader to a DataTable:
dr = command.ExecuteReader() ' Get Data Reader Rows
dt.Load(dr) 'Convert DataReader into DataTable
Which now could be bind to your Label or TextBox:
Label2.DataBindings.Add("Text", dt, "fname")
You don't need then to use HasRows property to check if DataReader has rows, instead you could check the Row Count of your DataTable:
If (dt.Rows.Count > 0) Then
Label2.DataBindings.Add("Text", dt, "fname")
End If
I am also using the Using statement in dotNet specially for connection so that you don't have to close:
Using connection As New MySqlConnection(connectionString)
'More code here
End Using ' Close the connection automatically
Check Complete Code Below:
Imports MySql.Data.MySqlClient
Public Class Form16
Dim connectionString as String = "server = localhost; user id = root;password=root; database = db"
Dim dt as DataTable
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Using connection As New MySqlConnection(connectionString)
' Use Parameterized query
Dim commandText as String = "SELECT * FROM Voter WHERE idn=#idn"
Dim command As New MySqlCommand(commandText, connection)
Dim dr As MySqlDataReader
' Add idn value using parameterized query
command.Parameters.AddWithValue("#idn", TextBox1.Text)
Try
connection.Open() ' Open Connection
dr = command.ExecuteReader()
dt = New DataTable()
dt.Load(dr)
If (dt.Rows.Count > 0) Then
Label2.DataBindings.Add("Text", dt, "fname")
Label10.DataBindings.Add("Text", dt, "mi")
Label11.DataBindings.Add("Text", dt, "lname")
Label12.DataBindings.Add("Text", dt, "yr")
Label13.DataBindings.Add("Text", dt, "sec")
Label14.DataBindings.Add("Text", dt, "vstatus")
Else
MessageBox.Show("Invalid ID No.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Using
End Sub
End Class
You have done more work than you have to...if you are going to use a datareader, your code should end up looking something like this. (I have not tested this code)
Imports MySql.Data.MySqlClient
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;database=db")
Dim DataSet1 As New DataSet
Dim dr As MySqlDataReader
Dim da As New MySqlDataAdapter
Dim cmd As New MySqlCommand
con.ConnectionString = "server = localhost; user id = root;password=root; database = db"
cmd.Connection = con
con.Open()
cmd.CommandText = "select * from voter where idn='" & TextBox1.Text & "'"
dr = cmd.ExecuteReader
con.Close()
if dr.read then
Label2.text = dr("fname")
Label10.text = dr("mi")
Label11.text = dr("lname")
Label12.text = dr("yr")
Label13.text = dr("sec")
Label14.text = dr("vstatus")
else
MessageBox.show("Invalid ID Number")
endif
End Class
I need your help, guys. I'm having an error. Please see my code below:
Imports MySql.Data.MySqlClient
Public Class frmlogin
Dim conn As MySqlConnection = New MySqlConnection
Dim serverstring As String = "Server=localhost;User Id=root;Password=root;Database=dasystem"
Dim login As Boolean
Dim ds As DataSet
Dim cusds As DataSet
Dim da As MySqlDataAdapter
Dim dt As DataTable
Dim ctrshowlogin, ctrshowsearch As Integer
Private Sub btnlogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click
Dim rowctr As Integer
Dim password As String
ctrshowlogin = 0
ds = New DataSet
da = New MySqlDataAdapter("select * from password", conn)
da.Fill(ds, "pword")
If cmbuser.SelectedItem = "Administrator" Then
For rowctr = 0 To ds.Tables(0).Rows.Count - 1
password = ds.Tables(0).Rows(rowctr).Item(0).ToString
If password = txtpass.Text Then
login = True
End If
Next (rowctr)
If login = True Then
MessageBox.Show("Login Successful!")
frmcomodities.Show()
Me.Hide()
cmbuser.Text = ""
ElseIf login = False Then
MessageBox.Show("Wrong Password, Please try again.")
txtpass.Focus()
End If
End If
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Close()
End Sub
End Class
Any ideas? I'm stuck with this problem. If you could help, I'd gladly appreciate it. Thanks.
You need to either change the name of the table in the da.Fill(ds, "pword") line to match the database table name (password):
da.Fill(ds, "password")
or just remove that parameter altogether
da.Fill(ds)