【发布时间】:2016-07-29 14:31:13
【问题描述】:
当我尝试我的代码更新 GridViewBox 以更新到我的数据库时,我收到以下错误消息
对象引用未设置为对象的实例
但我无法完全弄清楚。将不胜感激我能得到的任何帮助。
Imports MySql.Data.MySqlClient
Public Class Form1
//GLOBAL DELARATION
Dim conString As String = "Server=xxx;" & "Database=xxx;" & "Uid=xxx;" & "xxx;"
Dim con As New MySqlConnection(conString)
Dim cmd As MySqlCommand
Dim adapter As MySqlDataAdapter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
//TODO: This line of code loads data into the 'OlejnaDataSet.people' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.OlejnaDataSet.people)
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub hent()
Me.PeopleTableAdapter.Fill(Me.OlejnaDataSet.people)
End Sub
Private Sub cleartxt()
TextBox_name.Text = ""
TextBox_position.Text = ""
TextBox_team.Text = ""
End Sub
Private Sub Add()
Dim sql As String = "INSERT INTO people(Name,Position,Team) VALUES(@NAME,@POSITION,@TEAM)"
cmd = New MySqlCommand(sql, con)
//PARAMETERS
cmd.Parameters.AddWithValue("@NAME", TextBox_name.Text)
cmd.Parameters.AddWithValue("@POSITION", TextBox_position.Text)
cmd.Parameters.AddWithValue("@TEAM", TextBox_team.Text)
//Open Connection and INSERT
Try
con.Open()
If cmd.ExecuteNonQuery() > 0 Then
MsgBox("Added")
cleartxt()
End If
con.Close()
hent()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
//UPDATE DATABASE
Private Sub UpdateDG(id As String)
Dim sql As String = "UPDATE people SET name='" + TextBox_name.Text + "', position='" + TextBox_position.Text + "', team='" + TextBox_team.Text + "' WHERE ID='" + id + "'"
//Open CON, EXECUTE UPDATE, CLOSE
Try
con.Open()
adapter.UpdateCommand = con.CreateCommand()
adapter.UpdateCommand.CommandText = sql
If adapter.UpdateCommand.ExecuteNonQuery() > 0 Then
MsgBox("You have now updated")
cleartxt()
End If
con.Close()
//REFRESH
hent()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
Add()
End Sub
Private Sub ButtonDelete_Click(sender As Object, e As EventArgs) Handles ButtonDelete.Click
End Sub
Private Sub ButtonUpdate_Click(sender As Object, e As EventArgs) Handles ButtonUpdate.Click
Dim id As String = DataGridView1.SelectedRows(0).Cells(0).Value
UpdateDG(id)
End Sub
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim name As String = DataGridView1.SelectedRows(0).Cells(1).Value
Dim position As String = DataGridView1.SelectedRows(0).Cells(2).Value
Dim team As String = DataGridView1.SelectedRows(0).Cells(3).Value
TextBox_name.Text = name
TextBox_position.Text = position
TextBox_team.Text = team
End Sub
End Class
【问题讨论】:
-
您在哪一行得到了错误?
-
我直接从 GridView 得到错误 - 表单仍在运行:postimg.org/image/4a2dzp8vn
标签: mysql vb.net datagridview