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

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();

I had a public Ienumerable collection which is appended everytime when the function is called. So by overwriting it i flushed the Data in my Datagrid..


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();

Need Your Help

How to export mysql table to csv or excel file using phpExcel in CODEIGNITER

codeigniter phpexcel

I've been searching on how to export mysql table to csv or excel file. I've seen some steps and I followed them. Is there a way on how to export the mysql table to csv or excel file using codeignit...

Execute cmdlets on a 64bit Powershell executable

powershell 64bit remote-server cmdlets

How can i write a powershell script that opens and runs cmdlets on a 64bit remote powershell executable.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.