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条回答
Rolldiameter
2楼-- · 2019-02-01 21:29

Follow the easy way like this

assume that ta is a DataTable

ta.clear()
DataGridView1.DataSource = ta
DataGridView1.DataSource = Nothing
查看更多
小情绪 Triste *
3楼-- · 2019-02-01 21:29

I've got this code working in a windows form,

Public Class Form1

    Private dataStuff As List(Of String)


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        DataGridView1.DataSource = Nothing

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        dataStuff = New List(Of String)

        dataStuff.Add("qwerty")
        dataStuff.Add("another")
        dataStuff.Add("...and another")

        DataGridView1.DataSource = dataStuff
    End Sub
End Class
查看更多
做个烂人
4楼-- · 2019-02-01 21:30

When feeding info from an SQL query into a datagridview you can clear the datagridview first before reloading it.

Where I have defined dbDataSet as New DataTable I can do a clear. dbDataSet must be at the start of the form within the Public Class Form

Dim dbDataset AS New DataTable

within the code of you Private Sub, place

dbDataSet.Clear()
查看更多
虎瘦雄心在
5楼-- · 2019-02-01 21:31

For unbound cases note that:

DataGridView.Rows.Clear()

leaves the Columns collection in place.

DataGridView.Columns.Clear()

..will remove all the columns and rows. If you are using the DGV unbound, and on next use the columns change, clearing the Rows may not be adequate. For library code clear all the columns before adding columns.

查看更多
ら.Afraid
6楼-- · 2019-02-01 21:31

just write this

DataGridView1.DataSource = ""
查看更多
Rolldiameter
7楼-- · 2019-02-01 21:35

You should remove the table from dataset if the datagrid is bind to some datatable. Your Gridview will be cleared automatically. No other way.

[YourDatasetName].Tables.Clear()
查看更多
登录 后发表回答