Clear datagrid values in wpf
I need to flush my datagrid everytime when a treeviewitem is clicked. My code is given below.
But everytime when I click a treeview item datagrid is not cleared— it’s appended with incoming data. I used both dataGrid1.Columns.Clear() and dataGrid.ItemSource= null; How can i do this??
![]()
6 Answers 6
If you are populating the DataGrid by using:
Then you should be able to use:
To remove all the rows.
If you are binding to the ItemsSource like:
Then you should be able to set the ItemsSource to null and it will remove all the rows.
Как очистить datagrid c wpf
![]()
Лучший отвечающий
Вопрос
Использую c#, wpf, DataGrid, SqlDataAdapter, DataTable, MS Sql server
Для неё не могу реализовать: 1) удаление выделенных в DataGrid строк как через кнопку, так и через горячую клавишу Delete (метод Button_DeleteSelectedMark_Click ), 2) обновление строк DataGrid, если в фокусе находится основная форма и нажата клавиша F5 (метод Window_Marks_PreviewKeyDown ), 3) так же интересует реализация вставки, удаления (уже писал выше), изменения строк клавишами (горячими) из самой DataGrid (т.е. без использования дополнительных кнопок на форме как у меня).
Буду признателен, если подскажите какие события надо отлавливать при работе с DataGrid. Еще сомнения вызывает правильность реализации "Удалить все", может есть другой метод, не такой грубый ) Ну и так же принимаются советы по улучшению кода, критика.
How to clear values in a datagrid in C# wpf?
![]()
I want to clear the existing values in the data grid and load a new set of values when a button is clicked. This is what I've done.
But it doesn't clear and the values will be added to the existing list of data.. I know I'm missing something and this is really giving me a hard time for the last few days.. Help would be greatly appreciated..
![]()
You should use the following guides when working with new WPF controls, it'll at least put you in a working direction to begin with: http://www.wpftutorial.net/datagrid.html
So to specifically answer your setup.
Make sure you set the DataContext in the code behind.
You should make the collection a public property of the code behind class.
In this case I've initialized the property inline, you could do that initialization in the constructor instead if you wanted.
You don't need to bind the collection more than once and you can do this directly in XAML. Then you can delete your "gridMididDetails.Items.Refresh(); gridMidiDetails.ItemSource = . " code.
Then when you click your button you can just clear the list and add to it again