Clear datagrid values ​​in wpf

I need to wash mine datagridevery time I press treeviewitem. My code is below.

private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    this.dataGrid1.Columns.Clear();
    this.dataGrid1.ItemsSource= null;
    String path =this.treeView1.SelectedItem;
    if (!File.Exists(path))
        MessageBox.Show("Not Found");
    else
    {
        ob.provider(path);

        //   String data = @"C:\logs.xml";
        string data = path;
        objref.functionality(data);
        this.dataGrid1.ItemsSource = objref.Result;
    }
}

But every time I click on a treeview element, the datagrid is not cleared - it is added with the input. I used both dataGrid1.Columns.Clear(), and dataGrid.ItemSource= null; How can I do this?

+9
source share
6 answers

If you populate a DataGrid using:

dataGrid.Items.Add(someObject);

Then you can use:

dataGrid.Items.Clear(); 

To delete all rows.

If you are attached to ItemsSource, for example:

dataGrid.ItemsSource = someCollection;

Then you should be able to set the ItemsSource to null and delete all rows.

EDIT:

Remember to update it:

dataGrid.Items.Refresh();
+26
source

You can use a class ObservableCollection<>, not IEnumerable<>.

ObservableCollection<User> users = new ObservableCollection<User>();
dataGrid1.ItemsSource = users;

datagrid, .

users.Clear();
+3

I tried several approaches, and this was by far the best and most reliable:

dataGrid.Columns.Clear();
dataGrid.Items.Clear();
dataGrid.Items.Refresh();
+3
source

I had an open collection IEnumerablethat is added every time a function is called. Thus, overwriting it, I dumped the data into my Datagrid.

0
source

I was able to clear my Data-Grid by setting the DataContext to null.

DataGrid.DataContext=null;
0
source

If it is associated with a Source Item, the easiest way is

dataGrid1.ItemSource = null;

0
source

All Articles