Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear datagrid values in wpf

I need to flush my datagrid everytime when a treeviewitem is clicked. My code is given 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 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??

like image 340
BinaryMee Avatar asked Jan 23 '13 05:01

BinaryMee


3 Answers

If you are populating the DataGrid by using:

dataGrid.Items.Add(someObject);

Then you should be able to use:

dataGrid.Items.Clear(); 

To remove all the rows.

If you are binding to the ItemsSource like:

dataGrid.ItemsSource = someCollection;

Then you should be able to set the ItemsSource to null and it will remove all the rows.

EDIT:

Don't forget to refresh it:

dataGrid.Items.Refresh();
like image 75
Rhexis Avatar answered Sep 19 '22 02:09

Rhexis


You may consider using ObservableCollection<> class rather than IEnumerable<>.

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

You can clear the datagrid by using the below code.

users.Clear();
like image 39
klaydze Avatar answered Sep 21 '22 02:09

klaydze


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

dataGrid.Columns.Clear();
dataGrid.Items.Clear();
dataGrid.Items.Refresh();
like image 21
polfosol ఠ_ఠ Avatar answered Sep 20 '22 02:09

polfosol ఠ_ఠ