使用DataGridView进行第二次数据加载时出现问题。
这是我的DataGridView,在第一次加载数据时有一个删除按钮:
在第二次加载数据时,这是我得到的错误:
单击Ok
之后,这就是我的DataGridView中发生的情况:
删除按钮不见了。
这是我的代码:
Private Sub loaddata()
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
con.ConnectionString = "server=192.168.1.10;database=orderingsystem;username=server;password=server"
Dim da As New MySqlDataAdapter
Dim ds As New DataTable
Dim source As New BindingSource
Try
con.Open()
Dim query As String
Dim total As Double
Dim btn As New DataGridViewButtonColumn
btn.HeaderText = "Action"
btn.Text = "Delete"
btn.Name = "btn"
btn.UseColumnTextForButtonValue = True
query = "SELECT prodID, SUM(prodQty) as QTY, prodname as Name, prodPrice*SUM(prodQty) as Total from orderedlist where table_name = '" & Form1.Table_1.Name & "' GROUP BY prodID"
cmd = New MySqlCommand(query, con)
da.SelectCommand = cmd
da.Fill(ds)
source.DataSource = ds
dgv_myOrder.DataSource = ds
dgv_myOrder.Columns(0).Visible = False
For i As Integer = 0 To dgv_myOrder.Rows.Count - 1
total += Convert.ToDecimal(dgv_myOrder.Rows(i).Cells(3).Value).ToString("0.00")
Next
dgv_myOrder.Columns.Add(btn)
lbl_Total.Text = Decimal.Parse(total).ToString("0.00")
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Private Sub dgv_myOrder_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv_myOrder.CellClick
If e.RowIndex = dgv_myOrder.NewRowIndex Or e.RowIndex < 0 Then
ElseIf e.ColumnIndex = dgv_myOrder.Columns("btn").Index Then
Dim connection As String = "server=192.168.1.10;database=orderingsystem;username=server;password=server;"
Dim con2 As New MySqlConnection(connection)
con2.Open()
Dim data As String = dgv_myOrder.SelectedRows(0).Cells(0).Value.ToString
Label2.Text = data
Dim rd2 As MySqlDataReader
Dim cmd2 As New MySqlCommand("UPDATE orderedlist SET cancelstatus = 1 WHERE prodID = '" & Label2.Text & "' and table_name = '" & Form1.Table_1.Name & "'", con2)
rd2 = cmd2.ExecuteReader
con2.Close()
con2.Open()
Dim rd3 As MySqlDataReader
Dim cmd3 As New MySqlCommand("UPDATE tableassistance SET cancellation = 1 WHERE table_name = '" & Form1.Table_1.Name & "'", con2)
rd3 = cmd3.ExecuteReader
MessageBox.Show("Wait for confirmation!", "System")
Me.Close()
Label2.Text = ""
End If
End Sub
我在加载表单时致电 loaddata()
。
答案 0 :(得分:0)
首先删除此行:
dgv_myOrder.Columns.Add(btn)
不要在代码内部的datagridview中添加按钮,而是从设计器中创建按钮并将其用于其他列。
步骤:
1。使用datagridview右上角的添加列按钮创建所有datagrdiview列
2。添加列之后,将每个列像这样绑定到数据库中与其相关的列,当您在datagidview设计器中单击EditColumns并在每个列的属性中更改DataPropertyName
时,可以得到此窗口。将其更改为您要预览的数据表列名称的名称,而不是将其添加到“删除列”按钮上:
3。转到datagridview中“删除”按钮列的属性,您将在其中找到名为DefalutCellStyle
的属性,NullValue
会将其更改为“删除”。