VB.NET: Clear DataGridView - Stack Overflow

    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Jobs
    7. Discussions
    8. Collectives
    9. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Try Teams for free Explore Teams
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams VB.NET: Clear DataGridView Ask Question Asked 14 years, 9 months ago Modified 3 years ago Viewed 332k times 30

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?

Share Improve this question Follow edited Jul 3, 2020 at 12:13 braX's user avatar braX 11.7k5 gold badges22 silver badges37 bronze badges asked Feb 7, 2010 at 15:08 Bibhas Debnath's user avatar Bibhas DebnathBibhas Debnath 14.9k18 gold badges69 silver badges96 bronze badges Add a comment |

28 Answers 28

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 72

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() Share Improve this answer Follow answered Sep 16, 2010 at 12:55 Alex Essilfie's user avatar Alex EssilfieAlex Essilfie 12.6k9 gold badges74 silver badges108 bronze badges 1
  • 1 In case this code throws an error like "Cannot clear this list", I suggest this approach: DataGridView.DataSource = Nothing ...then refresh it... DataGridView.Refresh() – Curbside Coder Commented Oct 5, 2019 at 13:04
Add a comment | 11

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.

Share Improve this answer Follow answered Apr 8, 2013 at 20:38 rheitzman's user avatar rheitzmanrheitzman 2,2973 gold badges20 silver badges36 bronze badges 1
  • Thank goodness someone has included the code to clear unbound grid. I'm really glad there isn't a clear for the whole grid, too easy that way. – EllieK Commented Apr 28, 2023 at 18:06
Add a comment | 8

I'd probably use this...

DataGridView1.Rows.Clear()

to clear out the rows and then rebind.

Share Improve this answer Follow answered Feb 7, 2010 at 15:12 Restore The Data Dumps Again's user avatar Restore The Data Dumps AgainRestore The Data Dumps Again 39.3k12 gold badges99 silver badges124 bronze badges 1
  • 3 It says cannot clear this list.. Is it because I'm using a database table as the datasource? – Bibhas Debnath Commented Feb 7, 2010 at 23:25
Add a comment | 4

Follow the easy way like this

assume that ta is a DataTable

ta.clear() DataGridView1.DataSource = ta DataGridView1.DataSource = Nothing Share Improve this answer Follow edited Feb 5, 2013 at 10:35 Alex Essilfie's user avatar Alex Essilfie 12.6k9 gold badges74 silver badges108 bronze badges answered Jan 24, 2013 at 15:02 Nal MEN's user avatar Nal MENNal MEN 411 bronze badge Add a comment | 1

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

Share Improve this answer Follow answered Feb 7, 2010 at 15:13 FiveTools's user avatar FiveToolsFiveTools 6,03016 gold badges64 silver badges84 bronze badges 0 Add a comment | 1

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.

Share Improve this answer Follow edited May 31, 2013 at 16:34 Community's user avatar CommunityBot 11 silver badge answered May 31, 2013 at 16:14 karthikeyan's user avatar karthikeyankarthikeyan 112 bronze badges Add a comment | 1

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() Share Improve this answer Follow answered Sep 4, 2013 at 19:00 Ron Rebennack's user avatar Ron RebennackRon Rebennack 2,8141 gold badge23 silver badges19 bronze badges 1
  • Thumb up for mentioning a common problem, that other answers don't respect or address. – Oak_3260548 Commented Feb 16, 2018 at 8:49
Add a comment | 1

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.

Share Improve this answer Follow answered Jun 25, 2015 at 12:54 leoraelkins's user avatar leoraelkinsleoraelkins 1731 gold badge1 silver badge13 bronze badges Add a comment | 1

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

Share Improve this answer Follow edited Feb 14, 2017 at 17:21 marc_s's user avatar marc_s 752k183 gold badges1.4k silver badges1.5k bronze badges answered Jun 7, 2014 at 12:03 user3717731's user avatar user3717731user3717731 111 bronze badge 1
  • It's always better to explain why, not just what to do. – edi9999 Commented Jun 7, 2014 at 12:44
Add a comment | 0

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 Share Improve this answer Follow answered Feb 7, 2010 at 15:22 bristows's user avatar bristowsbristows 7461 gold badge7 silver badges22 bronze badges Add a comment | 0

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() Share Improve this answer Follow answered Jan 3, 2012 at 5:10 Samiran Nath's user avatar Samiran NathSamiran Nath 211 bronze badge 1
  • What does your answer adds new to the already accepted answer? – Yaroslav Commented Oct 27, 2012 at 16:14
Add a comment | 0

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

Share Improve this answer Follow answered Oct 28, 2013 at 9:54 Shaheed Muhammad's user avatar Shaheed MuhammadShaheed Muhammad 151 silver badge7 bronze badges Add a comment | 0

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

Share Improve this answer Follow answered Mar 7, 2014 at 13:50 Limanidt's user avatar LimanidtLimanidt 1 Add a comment | 0

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() Share Improve this answer Follow edited Jun 15, 2014 at 10:35 brasofilo's user avatar brasofilo 26k15 gold badges93 silver badges184 bronze badges answered Jun 15, 2014 at 7:21 user3741825's user avatar user3741825user3741825 1 Add a comment | 0

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.

Share Improve this answer Follow answered Jul 3, 2014 at 15:04 Charlie Marlin's user avatar Charlie MarlinCharlie Marlin 1 Add a comment | 0

If the DataGridView is bound to any datasource,

DataGridView1.DataSource = Nothing DataGridView1.DataBind() Share Improve this answer Follow answered Sep 10, 2014 at 14:18 SUHAIL AG's user avatar SUHAIL AGSUHAIL AG 1951 silver badge8 bronze badges Add a comment | 0 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 Share Improve this answer Follow edited Sep 4, 2015 at 11:03 Aleksandr M's user avatar Aleksandr M 24.4k13 gold badges74 silver badges146 bronze badges answered Sep 4, 2015 at 10:45 Michał R's user avatar Michał RMichał R 162 bronze badges Add a comment | 0

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

gvArchive.DataSource = Nothing gvArchive.DataBind() Share Improve this answer Follow edited Apr 11, 2016 at 17:55 Paul Roub's user avatar Paul Roub 36.4k27 gold badges85 silver badges93 bronze badges answered Apr 11, 2016 at 17:44 Neil's user avatar NeilNeil 8491 gold badge10 silver badges17 bronze badges Add a comment | 0

just write this

DataGridView1.DataSource = "" Share Improve this answer Follow answered Mar 26, 2017 at 10:20 Areej Qasrawi's user avatar Areej QasrawiAreej Qasrawi 974 bronze badges 1
  • 2 Whilst this code snippet is welcome, and may provide some help, it would be greatly improved if it included an explanation of how and why this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Commented Mar 27, 2017 at 10:18
Add a comment | 0

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.

Share Improve this answer Follow answered Sep 20, 2017 at 12:57 Barbora's user avatar BarboraBarbora 12 bronze badges Add a comment | 0

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 Share Improve this answer Follow answered Dec 22, 2017 at 19:45 Meisam Rasouli's user avatar Meisam RasouliMeisam Rasouli 3212 silver badges6 bronze badges Add a comment | 0

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.

Share Improve this answer Follow answered Feb 7, 2019 at 4:46 D.Bhardwaj's user avatar D.BhardwajD.Bhardwaj 11 bronze badge Add a comment | -1

You can do in this way:

DataGridView1.Enable = false DataGridView1.DataSource = Nothing DataGridView1.Enable = true Share Improve this answer Follow edited Mar 20, 2012 at 15:47 Isuru's user avatar Isuru 31.2k63 gold badges190 silver badges311 bronze badges answered Feb 1, 2012 at 9:21 wertyk's user avatar wertykwertyk 40810 silver badges31 bronze badges Add a comment | -1

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() Share Improve this answer Follow edited Feb 25, 2014 at 4:52 answered Feb 24, 2014 at 10:56 user2955140's user avatar user2955140user2955140 11 bronze badge 1
  • Thanks for contributing to StackOverflow :). The question you are answering is old and already answered - we'll be glad if you can give your effort to more pressing questions too. Also please try to keep your answer relevant for the example in the question (which doesn't involve any users table, for instance). – Mifeet Commented Feb 24, 2014 at 11:20
Add a comment | -1

You can do that only by the following 2 lines:

DataGridView1.DataSource=Nothing DataGridView1.DataBind() Share Improve this answer Follow edited Jun 7, 2016 at 13:16 Thomas G's user avatar Thomas G 10.2k7 gold badges31 silver badges44 bronze badges answered Jun 7, 2016 at 7:42 Peter Mankge's user avatar Peter MankgePeter Mankge 791 silver badge2 bronze badges Add a comment | -1

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

DataGridView1.DataSource.Clear() Share Improve this answer Follow edited Mar 7, 2018 at 3:51 answered Mar 7, 2018 at 3:22 Dash_25's user avatar Dash_25Dash_25 11 bronze badge Add a comment | -1

Try this for a specific cell:

Datagrid.Rows(RowIndex).Cells(ColIndex).Value = DBNull.Value Share Improve this answer Follow edited Jun 15, 2020 at 17:40 Matt Ke's user avatar Matt Ke 3,72912 gold badges33 silver badges51 bronze badges answered Jun 15, 2020 at 17:04 ahmed abdelsalam's user avatar ahmed abdelsalamahmed abdelsalam 1 1
  • Very short answers tend to get automatically flagged for low quality, so avoid one-liner answers like this. Beyond that, it's always helpful to add a little explanation of why the change you're suggesting should solve the problem. – Caleb Commented Jun 15, 2020 at 18:05
Add a comment | -1

DgRemolques is the name of my Data grid on WPF

dgRemolques.ItemsSource = Nothing but i need to clean also de DataTable dtRemolques.Clear()

Share Improve this answer Follow edited Oct 27, 2021 at 23:42 answered Oct 22, 2021 at 16:42 Gmo Core's user avatar Gmo CoreGmo Core 11 bronze badge 1
  • 1 Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. – Community Bot Commented Oct 22, 2021 at 17:08
Add a comment |

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved Draft discarded

Sign up or log in

Sign up using Google Sign up using Email and Password Submit

Post as a guest

Name Email

Required, but never shown

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.

  • The Overflow Blog
  • The open-source ecosystem built to reduce tech debt
  • Featured on Meta
  • More network sites to see advertising test
  • We’re (finally!) going to the cloud!
  • Call for testers for an early access release of a Stack Overflow extension...

Linked

0 Clear DataGridView with rows and headers structure of dataset bind 0 refresh button for datagridview 0 How to remove a table in a DataSet and then add new table with the same name? (C# - Winforms) 62 DataGridView.Clear() 0 How to clear data in DataGridView? 46 How to clear a data grid view 10 How to empty a datagridview? 0 Datagridview should not clear on datasource = nothing 1 How to clear DataGrid rows 0 c# clear datagridview bound to datasource 0 How to clear DataGridView in C# windows forms? 0 How to delete and clear the datagridview rows in vb 2010 2 DataGridView & datasource will not clear

Hot Network Questions

  • Does the ZX Spectrum's system variable PROG always hold 23755 (5CCBh)?
  • Doubt on construction of phase oracle in Grover's Algorithm
  • How to interpret Frequency Response spec of Studio Monitor speakers
  • Algebraic theorems with no known algebraic proofs
  • How to assess differences between tensor product smooths?
  • How can Amos Hochstein visit both Lebanon and Israel without violating either country's laws?
  • Could not find add method: AddExcludedTemplate (type: Sitecore.ContentSearch.SolrProvider.SolrIndexConfiguration)
  • Should I Continue Studying Buffer Overflow Vulnerabilities?
  • Does Ukraine consider itself to be at war with North Korea?
  • A kind of "weak reference" which keeps the object alive, as long as there is otherwise-unused memory
  • Cashless visit to Schengen countries using USA credit card
  • Cyclic Radioactivity
  • Why do researchers wear white hats when handling lunar samples?
  • How to re-mean a vector of probabilities, without having values beyond the [0, 1] bounds?
  • Spanish train pre-ordered meals and special diets
  • Noun+なの, when の is the indefinite pronoun?
  • Can A Fairy Fly With A Magical Breastplate Weighing 10 lbs?
  • Is it ever possible that the object is moving with a velocity such that its rate of change of speed is not constant but acceleration is constant?
  • Is there any incentive for the 100 answerers to get the questions right?
  • Is there a well-known digital logic circuit that outputs the last valid input on a high impedence input?
  • Examples of countries that decided whether to change their voting rule?
  • Switched to Gas from Induction, hate it, is it the range?
  • Draw stroke only outside of the path in TikZ
  • creating named control sequences
more hot questions Question feed Subscribe to RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-vb

Từ khóa » Visual Basic Clear Gridview