如何在vb.net中更新后刷新datagridview

时间:2013-02-12 18:39:53

标签: vb.net winforms datagridview

这是我的代码:

        Dim sqledit As New SqlCommand
        sqledit = New SqlCommand("UPDATE Branches SET StAddress='" + txtstaddress.Text + "',City='" + txtcity.Text + "',Province='" + txtprovince.Text + "',ContactNo='" + txtcontact.Text + "' WHERE BranchID='" + txtbranchid.Text + "'", con1)
        sqledit.ExecuteNonQuery()
        MsgBox("Branch Information Updated!", MsgBoxStyle.Information, Title:="Edit Branch Information")
        utilities.Refresh()
        Me.Close()

即使我刷新它也无法更新它。请帮忙!

2 个答案:

答案 0 :(得分:1)

也有简单的方法 您可以通过调用所有表内容的datagridview进行查询 例如:

SELECT {your table field}
FROM {table name}

如果您在更改后执行此查询,它将在DGV上显示新数据。

答案 1 :(得分:0)

实现此目的的最佳方法是重新加载数据网格视图。以下是解释如何操作的代码

Private Sub refreshDatagrid()
    Dim con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=reerp;User ID=root;Password=root;")
    Dim sql As MySqlCommand = New MySqlCommand("SELECT * FROM users", con)
    Dim ds As DataSet = New DataSet()
    Dim DataAdapter1 As MySqlDataAdapter = New MySqlDataAdapter()
    con.Open()
    DataAdapter1.SelectCommand = sql
    DataAdapter1.Fill(ds, "Users")
    DataGridView1.DataSource = ds
    DataGridView1.DataMember = "Users"
    con.Close()

End Sub

现在,当您向网格添加数据后,再次调用此方法。这是你如何做的例子

   Dim query As String
    Dim con As MySqlConnection = New MySqlConnection("data source=localhost;database=reerp;user id=root;password=root;")

    query = "insert into users (username,password,first_name,last_name,role) values('"
    query = query + tb_username.Text + "','" + tb_password.Text + "','" + tb_firstname.Text + "','" + tb_lastname.Text + "','" + ComboBox_role.Text + "');"
    con.Open()

    Dim cmd As MySqlCommand = New MySqlCommand(query, con)

    Dim i As Integer = cmd.ExecuteNonQuery()
    If (i > 0) Then
        lblMsg.Text = "record is successfully inserted"
        refreshDatagrid()

    Else
        lblMsg.Text = "record is not inserted"
    End If
    con.Close()