VB.NET: Clear DataGridView

2019-02-01 21:02发布

I've tried -

DataGridView1.DataSource=Nothing

and

DataGridView1.DataSource=Nothing
DataGridView1.Refresh()

and

DataGridView1.RefreshEdit()

None of them works..

I've written a method that sets the DataSource of the DataGridView when executed. but each time i execute it, it replicates the data with new value and appends it to the previous contents of the DGV.. I wanna clear the content and then add the values.. Is that possible?

25条回答
唯我独甜
2楼-- · 2019-02-01 21:44

If the DataGridView is bound to any datasource, you'll have to set the DataGridView's DataSource property to Nothing.

If the DataGridView is not bound to any data source, this code will do the trick:

DataGridView.Rows.Clear()
查看更多
对你真心纯属浪费
3楼-- · 2019-02-01 21:44

Can you not bind the datagridview to an empty collection (instead of null). That do the trick?

查看更多
smile是对你的礼貌
4楼-- · 2019-02-01 21:47

I'd probably use this...

DataGridView1.Rows.Clear()

to clear out the rows and then rebind.

查看更多
倾城 Initia
5楼-- · 2019-02-01 21:47

If the GridView (Say the name is gvArchive) is bound to any DataSource, the following will clear it:

gvArchive.DataSource = Nothing

gvArchive.DataBind()
查看更多
你好瞎i
6楼-- · 2019-02-01 21:48

I found that setting the datasource to null removes the columns. This is what works for me:

c#:

((DataTable)myDataGrid.DataSource).Rows.Clear();

VB:

Call CType(myDataGrid.DataSource, DataTable).Rows.Clear()
查看更多
地球回转人心会变
7楼-- · 2019-02-01 21:49

My DataGridView is also bound to a DataSource and myDataGridView.Columns.Clear() worked fine but myDataGridView.Rows.Clear() did NOT. Just an FYI for those who have tried .Rows.

查看更多
登录 后发表回答