保存在vb.net中时如何刷新数据?

时间:2019-07-12 09:11:45

标签: vb.net

我想在单击保存按钮时刷新我的数据。我正在使用datagriedview,但不会自动刷新。我该如何编码?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim sql As String = "INSERT INTO tblproduct(product,Supplierprice,Projectprice) VALUES (@product,@Supplierprice,@Projectprice)"
    cmd = New MySqlCommand(sql, con)

    'parameters()

    cmd.Parameters.AddWithValue("@product", txtproductname.Text)
    cmd.Parameters.AddWithValue("@Supplierprice", txtsupprice.Text)
    cmd.Parameters.AddWithValue("@Projectprice", txtproprice.Text)

    Try
        con.Open()
        If MessageBox.Show("Are You Sure To Save This?", "SAVE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            If cmd.ExecuteNonQuery() > 0 Then
                MsgBox("Successfully Save")

            End If
        End If
        con.Close()

    Catch ex As Exception
        MsgBox(ex.Message)
        con.Close()

    End Try

    Refresh()

    Hide()

End Sub

1 个答案:

答案 0 :(得分:0)

这就是我要做的方式。

首先创建一个类。

Public Class Product
Public Sub New(productName As String, supplierPrice As String, projectPrice As String)
    Me.ProductName = productName
    Me.SupplierPrice = supplierPrice
    Me.ProjectPrice = projectPrice
End Sub

Public Property ProductName As String

Public Property SupplierPrice As String

Public Property ProjectPrice As String

End Class

声明该类的BindingList并将其用作数据源。添加项目时,只需添加到BindingList。网格将自动刷新。

Public Class Form1

Private Products As New BindingList(Of Product)

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    dgvProducts.DataSource = Products
End Sub

Private Sub bnAdd_Click(sender As Object, e As EventArgs) Handles bnAdd.Click
    Dim item As Product = New Product(tbProductName.Text, tbSupplierPrice.Text, tbProjectPrice.Text)

    If MessageBox.Show($"Are You Sure To Save the product : {item.ProductName}?", "SAVE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
        SaveProduct(item)
        Products.Add(item)
    End If

End Sub

Private Sub SaveProduct(item As Product)
    'Add database insert code
End Sub

End Class