如何在 vb.net 中更新后刷新 datagridview
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14839468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to refresh datagridview after update in vb.net
提问by tristan
Here is my code:
这是我的代码:
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()
I can't get to update it even if I refresh it. Please help!
即使我刷新它也无法更新它。请帮忙!
回答by mohsen
There is easy way too you can make a query by your datagridview that call all of your table content example:
您也可以通过调用所有表格内容示例的 datagridview 进行查询:
SELECT {your table field}
FROM {table name}
If you execute this query after changes it will show you the new data on DGV.
如果您在更改后执行此查询,它将向您显示 DGV 上的新数据。
回答by timberlake
The best way to achieve this is reload the data grid view. Here is the code that explains how to do it
实现此目的的最佳方法是重新加载数据网格视图。这是解释如何执行此操作的代码
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
now once you have added data to your grid then just call this method again. here is and example of how you do it
现在一旦你将数据添加到你的网格然后再次调用这个方法。这是你如何做的例子
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()

