Как очистить datagridview c полностью
Перейти к содержимому

Как очистить datagridview c полностью

  • автор:

How to clear a data grid view

I am trying to populate a DataGridView based on the selected item in a ComboBox, I have this part working.

However, I need to be able to clear the grid before adding the new data from a new item rather than it just adding on to the end.

How do I clear a DataGridView before adding items to it?

Wizard's user avatar

17 Answers 17

Firstly, null the data source:

Then clear the rows:

Then set the data source to the new list:

If it’s bound to a datasource —

You can clear DataGridView in this manner

If it is databound then try this

IF you want to clear not only Data, but also ComboBoxes, Checkboxes, try

nate wew's user avatar

You can assign the datasource as null of your data grid and then rebind it.

Rohit Vyas's user avatar

You could take this next instruction and would do the work with lack of perfomance. If you want to see the effect of that, put one of the 2 next instructions (Technically similars) where you need to clear the DataGridView into a try<> catch(. )<> finally block and wait what occurs.

You improve this task but its not enough, there is a problem to reset a DataGridView, because of the colums that remains in the DataGridView object. Finally I suggest, the best way i’ve implemented in my home practice is to handle this gridView as a file with rows, columns: a record collection based on the match between rows and columns. If you can improve, then take your own choice a) or b): foreach or while.

Well, as a recomendation Never in your life delete the columns first, the order is before the rows after the cols, because logically the columns where created first and then the rows.It would be a penalty in terms of correct analisys.

Then, Put it inside a function or method.

Finally, call your new function ClearDataGridViewLoopWhile(); or ClearDataGridViewForEach(); where you need to use it, but its recomended when you are making queries and changing over severall tables that will load with diferents header names in the grieView. But if you want preserve headers here there is a solution given.

Как очистить datagridview c полностью

Не удается удалить этот список.

11 ответов

У меня также была аналогичная проблема, когда я пытаюсь очистить DataSource DataGridView после того, как привязал его к DataTable с помощью:

когда я попытаюсь очистить строки позже с помощью следующего кода:

Я получаю эту ошибку:

Эта объектная ссылка Проблема ERROR уже решена в здесь. Но мне удалось решить мою собственную проблему (очистка строк DataGridView) с помощью этого кода:

Я знаю, что этот вопрос был задан очень давно, но я надеюсь, что мое решение решит проблемы.

Очистка DataGridView или удаление всех записей

Сейчас разрабатываю приложение, которое работает с базой данных и производит вывод информации в элемент DataGridView . И на одном из этапов разработки мне понадобилось очистить весь DataGridView. Вроде бы элементарная задача, однако решить её первым возникшим у меня в голове способом мне не удалось.

Начнем с того, что метод Clear() не работает.

Тогда на помощь приходит цикл:

Производим удаление последней записи до тех пор, пока количество записей не будет равно нулю.

Как подсказали в комментариях, происходило это потому, что вероятно был биндинг с DataSource .
В таком случае стоит попробовать следующий вариант:

Но сейчас я бы предпочел получить BindingSource и очистить его.

Вот так нужно очищать DataGridView, если метод Clear() не срабатывает. Вот такой своеобразный клининг получился.

DataGridView.Clear()

Here comes the trouble. I want to delete all rows from datagridview. This how i add rows:

And its how i clear gridview:

in debug i see that dataGridVIew1.Rows.Count=0, but on form, grid doesnt become clear. what a point? on each selection in tree, i want to see new rows in table.

19 Answers 19

I’m betting you just need to refresh the datagrid. Try this:

If this works. you might want to rethink this part of your application.

If I remember correctly, I set the DataSource property to null to clear the DataGridView:

Как очистить datagridview c полностью

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Visual studio home link

  • ProfileText
  • Sign in
Answered by:
Question

I have a datagridview on a form. I required it to clear all rows of datagridview on button click event.

I tried the syntax ::

But that syntax threws an exception "Cannot Clear The List".

Currently i am using the syntax ::

Here, I want to know that is the method mentioned later is the appropriate to clear the datagridview rows or is their any other method to clear the datagridview rows.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *