Как очистить datagrid c wpf

от admin

how to clear data of datagrid in WPF

I am using dataGrid of WPF and populating through bservableCollection.

Now, for clean/clear the datagrid to use it again I used

but data are still showing and active in the table.

3 Answers 3

You have bind collection so, in WPF you have to clean collection then it will clean data grid because you have used observable collection.

to clear the rows of the DataGrid use:

to clear the columns:

Now, for clean/clear the datagrid to use it again I used dataGrid.items.Clear();

After that clear, try to bind a empty Collection.

And then refresh the Grid

That should do the trick.

Cataklysim's user avatar

    The Overflow Blog
Related
Hot Network Questions

Subscribe to RSS

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

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Как очистить datagrid c wpf

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

How can I clear a datagrid with one button click?

I need to do this using MVVM

Thanks in advance.

Answers

The most common way I see this done and the one I like the best is to use commanding on your button.

See Relaying Command Logic in this article for one way to do that:

Your DataGrids source should be an ObservableCollection<T> in your ViewModel, so you would then just call Clear on the collection from the Execute of the command.

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..

Читать:
Как починить машину в rage 2

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

Как очистить содержимое сетки WPF?

Я хочу очистить / удалить ВСЕ содержимое сетки, включая RowDefinitions, как я могу это сделать?

задан 22 июля ’11, 01:07

2 ответы

myGrid.Children.Clear() удалит все дочерние элементы управления, вложенные в сетку. myGrid.RowDefinitions.Clear() удалит все определения строк. myGrid.ColumnDefinitions.Clear() удалит все определения столбцов.

для полноты вы также можете добавлять / удалять отдельные элементы с помощью методов добавления / удаления соответствующих коллекций. myGrid.Children для управления, myGrid.RowDefinitions для определений строк и myGrid.ColumnDefinitions для колонн.

вся эта информация доступна здесь, в MSDN

Создан 23 июля ’11, 00:07

Однако после того, как я очищу дочерние элементы, количество строк и столбцов останется неизменным? Это хорошо очищено? — Трио Чунг

попробуйте выполнить цикл в свой контейнерный элемент управления (пример сетки) и в этом цикле проверьте тип элемента управления следующим образом:

ответ дан 13 мар ’15, в 09:03

Для модификации Wh будет нормально. Но если вы попытаетесь удалить содержимое из сетки, как первоначально просил OP, этот подход приведет к исключительному поведению, потому что вы попытаетесь изменить коллекцию во время итерации по ней. Кроме того, учитывая ваш код, я бы предложил полностью заменить сравнение строк для проверки типов, например, запрашивая только TextBoxes из коллекции Children следующим образом: foreach (TextBox c в YourContainer.Children.OfType ) — Кюпкер

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками wpf or задайте свой вопрос.

Похожие статьи