vb.net 执行 SQL 命令后刷新 DataGridView?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16628539/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:38:22  来源:igfitidea点击:

Refresh DataGridView after executing SQL Command?

vb.netdatagridview

提问by Caffe Latte

Here is my code:

这是我的代码:

 cn.Open()
     cmd.CommandText = "insert into Student values('" ......
      cmd.ExecuteNonQuery()
        cn.Close()

After closing the connection I want my DataGridView to refresh it's data's also.
I am new in VB.NET I tried datagridview.refresh()but it's not working as I think it's like repainting not updating it's data's.
Thanks.

关闭连接后,我希望我的 DataGridView 也刷新它的数据。
我是 VB.NET 的新手,我尝试过,datagridview.refresh()但它不起作用,因为我认为这就像重绘而不是更新它的数据。
谢谢。

采纳答案by Neolisk

If you update the underlying business object, the UI should update automatically. My guess it that you forgot to do data binding, for example DataGridView.DataSource = yourDataTable.

如果更新底层业务对象,UI 应自动更新。我猜你忘了做数据绑定,例如DataGridView.DataSource = yourDataTable

EDIT:the easiest way from where you are right now would probably be to replace this:

编辑:从你现在所处的位置最简单的方法可能是替换这个:

cmd.ExecuteNonQuery()

with this:

有了这个

Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())

and then:

进而:

DataGridView.DataSource = dt

If you need database updates, you may want to use a DataAdapterand its Updatemethod. The overload I linked is specifically for a DataTable, i.e. you don't need a DataSet, unless you have it already.

如果您需要数据库更新,您可能需要使用DataAdapter及其Update方法。我链接的重载专门用于 DataTable,即您不需要 DataSet,除非您已经拥有它。

回答by matzone

As @Neolisk said you have to do databinding .. for example

正如@Neolisk 所说,您必须进行数据绑定 .. 例如

Dim ds as DataSet
Dim sSql As New OleDb.OleDbCommand

sSql = cnEZApp.CreateCommand()

cmd = New Data.OleDb.OleDbDataAdapter("SELECT * FROM student ORDER by kode", conn)
cmd.Fill(ds, "student")
dgvGuru.DataSource = ds.Tables("student")

So, to update table as datasource you have to do

因此,要将表更新为数据源,您必须执行

sSql.CommandText = "insert into Student(...) values(...)"
cmd.UpdateCommand = sSql
cmd.UpdateCommand.ExecuteNonQuery()
cmd.ExecuteNonQuery()