[vb.net] VB.NET: Clear DataGridView

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?

This question is related to vb.net datagridview datasource datagridviewrow

The answer is


For the Clear of Grid View Data You Have to clear the dataset or Datatable

I use this Code I clear the Grid View Data even if re submit again and again it will work Example Dim con As New OleDbConnection Dim cmd As New OleDbCommand Dim da As New OleDbDataAdapter Dim dar As OleDbDataReader Dim dt As New DataTable If (con.State <> 1) Then con.Open() End If dt.Clear() 'To clear Data Every time to fresh data cmd.Connection = con cmd.CommandText = "select * from users" da.SelectCommand = cmd da.Fill(dt) DataGridView1.DataSource = dt DataGridView1.Visible = True

    cmd.Dispose()
    con.Close()

Dim DS As New DataSet

DS.Clear() - DATASET clear works better than DataGridView.Rows.Clear() for me :

Public Sub doQuery(sql As String)
   Try
        DS.Clear()  '<-- here
        '   - CONNECT -
        DBCon.Open()
        '   Cmd gets SQL Query
        Cmd = New OleDbCommand(sql, DBCon)
        DA = New OleDbDataAdapter(Cmd)
        DA.Fill(DS)
        '   - DISCONNECT -
        DBCon.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

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()

You can do in this way:

DataGridView1.Enable = false
DataGridView1.DataSource = Nothing
DataGridView1.Enable = true

I had the same problem: I was programmatically binding my GridView1 to one SQL table [dictonary] or another [meny] BUT when I selected the second table from my RadioButtonList1, I was getting an error (System.Web.HttpException: Field or property with the title [the first column's title from the previously selected table] was not found in the selected data source.) i.e. saying that the columns from my first-selected table couldn't be found. All I needed to do was insert:

GridView1.Columns.Clear()

before adding the table columns. Here goes the full code:

Dim connectionString As String = "your-string-details"
Dim connection As New SqlConnection(connectionString)

Then comes your first Sub:

Private Sub BindOrders()
    connection.Open()

    Dim sqlCommand As String = "SELECT * FROM [dictionary]" 
    Dim dataAdapter As New SqlDataAdapter(sqlCommand, connection)
    Dim dt As New DataTable() 
    dataAdapter.Fill(dt)

    GridView1.Columns.Clear() ' clear columns before adding new ones

    If GridView1.Columns.Count <= 0 Then
        Dim Field As New BoundField()
        Field.DataField = "id"
        Field.HeaderText = "id"
        GridView1.Columns.Add(Field)

        Field = New BoundField()
        Field.DataField = "strArHundreds"
        Field.HeaderText = "strArHundreds"
        GridView1.Columns.Add(Field)

        Field = New BoundField()
        Field.DataField = "strArTens"
        Field.HeaderText = "strArTens"
        GridView1.Columns.Add(Field)

        Field = New BoundField()
        Field.DataField = "strArSingles"
        Field.HeaderText = "strArSingles"
        GridView1.Columns.Add(Field)
    End If

    GridView1.DataSource = dt
    GridView1.DataBind()

    connection.Close()
End Sub

Then comes your second Sub:

Private Sub BindDocuments()
    connection.Open()

    Dim sqlCommand As String = "SELECT * FROM [meny]"
    Dim dataAdapter As New SqlDataAdapter(sqlCommand, connection)
    Dim dt As New DataTable()

    dataAdapter.Fill(dt)

    GridView1.Columns.Clear() ' clear columns before adding new ones

    If GridView1.Columns.Count <= 0 Then
        Dim Field As New BoundField
        Field = New BoundField
        Field.DataField = "id"
        Field.HeaderText = "id"
        GridView1.Columns.Add(Field)

        Field = New BoundField
        Field.DataField = "nazev"
        Field.HeaderText = "nazev"
        GridView1.Columns.Add(Field)
    End If

    GridView1.DataSource = dt
    GridView1.DataBind()

    connection.Close()
End Sub

Finally comes your RadioButton:

Protected Sub RadioButtonList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RadioButtonList1.SelectedIndexChanged
    Dim index As Integer
    index = RadioButtonList1.SelectedIndex
    Select Case index
        Case 0
            BindOrders()
            Exit Select
        Case 1
            BindDocuments()
            Exit Select
    End Select
End Sub

For completion, here is the code for the GridView1 and the RadioButtonList1 in the associated aspx.file:

<asp:RadioButtonList ID="RadioButtonList1"
    runat="server"
    AutoPostBack="True"
    OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
    <asp:ListItem>Obraty</asp:ListItem>
    <asp:ListItem>Dokumenty</asp:ListItem>
</asp:RadioButtonList>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>

This all works well now.


I had the same problem on gridview content clearing. The datasource i used was a datatable having no columns, and i added columns and rows programmatically to datatable. Then bind to datagridview. I tried the code related with gridview like gridView.Rows.Clear(), gridView.DataSource = Nothing

but it didn't work for me. Then try the below code related with datatable before binding it to datagridview each time.

  dtStore.Rows.Clear()
  dtStore.Columns.Clear()
  gridView.DataSource = dtStore

And is working fine, no replication in DataGridView


Follow the easy way like this

assume that ta is a DataTable

ta.clear()
DataGridView1.DataSource = ta
DataGridView1.DataSource = Nothing

The mistake that you are making is that you seem to be using a dataset object for storing your data. Each time you use the following code to put data into your dataset you add data to the data already in your dataset.

myDataAdapter.Fill(myDataSet)

If you assign the table in your dataset to a DataGridView object in your program by the following code you will get duplicate results because you have not cleared data which is already residing in your dataset and in your dataset table.

myDataGridView.DataSource = myDataSet.Tables(0)

To avoid replicating the data you have to call clear method on your dataset object.

myDataSet.clear()

An then assign the table in your dataset to your DataGridView object. The code is like this.

myDataSet.clear()
myDataAdapter.Fill(myDataSet)
myDataGridView.DataSource = myDataSet.Tables(0)

You can try this code:

' clear previous data
DataGridView2.DataSource = Nothing
DataGridView2.DataMember = Nothing
DataGridView2.Refresh()
Try
    connection.Open()
    adapter1 = New SqlDataAdapter(sql, connection)
    ' clear data already in the dataset
    ds1.Clear()
    adapter1.Fill(ds1)
    DataGridView2.DataSource = ds1.Tables(0)
    connection.Close()
Catch ex As Exception
    MsgBox(ex.ToString)
End Try

If the DataGridView is bound to any datasource,

DataGridView1.DataSource = Nothing
DataGridView1.DataBind()

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()

1) create button named it Clear.Inside insert tfhe following code datagridviewer.DataSource=nothing

2) In your search button begin your code by the following statement

datagridviewer.DataSource = DataSet.table

Nb:instead of table put the real name of your table ex: datagridviewer.DataSource = DataSet.client


Use this code where ever you want to implement clear datagridview command

datagridview1.datasource= nothing
datagridview1.datasource= ds
dt.clear()               'Dt as new DATATABLE
ds.clear()              'Ds as new Dataset

this code will clear the datagridview and wil stop data duplication when populating data from database.


To remove the old record in datagridview when you are searching for new result,with button_click event write the following code,

me.DataGridview1.DataSource.clear()

this code will help to remove the old record in datagridview.


Don't do anything on DataGridView, just clear the data source. I tried clearing myDataset.clear() method, then it worked.


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.


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

gvArchive.DataSource = Nothing

gvArchive.DataBind()

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.


You can do that only by the following 2 lines:

DataGridView1.DataSource=Nothing
DataGridView1.DataBind()

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()

just write this

DataGridView1.DataSource = ""

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


I'd probably use this...

DataGridView1.Rows.Clear()

to clear out the rows and then rebind.


You may have a user scenario such that you want to keep the data binding and only temporarily clear the DataGridView. For instance, you have the user click on a facility on a map to show its attributes for editing. He is clicking for the first time, or he has already clicked on one and edited it. When the user clicks the "Select Facility" button, you would like to clear the DataGridView of the data from the previous facility (and not throw an error if it's his first selection). In this scenario, you can achieve the clean DataGridView by adapting the generated code that fills the DataGridView. Suppose the generated code looks like this:

    Try
        Me.Fh_maintTableAdapter.FillByHydrantNumber(Me.Fh2010DataSet.fh_maint, hydrantNum)
    Catch ex As System.Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    End Try

We are filling the DataGridView based on the hydrant number. Copy this code to the point where you want to clear the DataGridView and substitute a value for "hydrantNum" that you know will retrieve no data. The grid will clear. And when the user actually selects a facility (in this case, a hydrant), the binding is in place to fill the DataGridView appropriately.


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

Try this for a specific cell:

Datagrid.Rows(RowIndex).Cells(ColIndex).Value = DBNull.Value

You can also try this code if you want to clear all data in your DataGridView

DataGridView1.DataSource.Clear()

Examples related to vb.net

How to get parameter value for date/time column from empty MaskedTextBox HTTP 415 unsupported media type error when calling Web API 2 endpoint variable is not declared it may be inaccessible due to its protection level Differences Between vbLf, vbCrLf & vbCr Constants Simple working Example of json.net in VB.net How to open up a form from another form in VB.NET? Delete a row in DataGridView Control in VB.NET How to get cell value from DataGridView in VB.Net? Set default format of datetimepicker as dd-MM-yyyy How to configure SMTP settings in web.config

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results

Examples related to datasource

Spring Boot Configure and Use Two DataSources Configure DataSource programmatically in Spring Boot Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional How to use JNDI DataSource provided by Tomcat in Spring? Using a list as a data source for DataGridView Binding Combobox Using Dictionary as the Datasource How to connect to a MySQL Data Source in Visual Studio VB.NET: Clear DataGridView c# dictionary one key many values How do I manually configure a DataSource in Java?

Examples related to datagridviewrow

VB.NET: Clear DataGridView