Clear datagrid values in wpf

后端 未结 7 1447
粉色の甜心
粉色の甜心 2021-01-11 19:14

I need to flush my datagrid everytime when a treeviewitem is clicked. My code is given below.

private void treeView1_SelectedItemCh         


        
相关标签:
7条回答
  • 2021-01-11 19:59

    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();
    
    0 讨论(0)
  • 2021-01-11 20:02

    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();
    
    0 讨论(0)
  • 2021-01-11 20:02

    You have to unbind the itemsource before you clear the item

    MyGrid.ItemsSource = null;**//un-bind the itemsource first**
    MyGrid.Items.Clear();**//**
    
    0 讨论(0)
  • 2021-01-11 20:04

    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();
    
    0 讨论(0)
  • 2021-01-11 20:07

    I had a public IEnumerable collection which is appended every time the function is called. So by overwriting it, I flushed the Data in my Datagrid.

    0 讨论(0)
  • 2021-01-11 20:11

    If it is bound an Itemsource, the simplest way is

    dataGrid1.ItemSource = null;

    0 讨论(0)
提交回复
热议问题