2
Answers

How to do DataGrid Column sort from code behind?

Ankita Goel

Ankita Goel

7y
207
1

I have a DataGrid in my project where I am hiding the column headers. When user clicks on a button, I want to sort grid based on first column.

I tried following code which is not working
  1. public MainWindow()  
  2.  {  
  3.      InitializeComponent();  
  4.      dataGrid1.Loaded += (s, e) =>  
  5.      {  
  6.         dataGrid1.Sorting -= DataGrid1_Sorting;  
  7.         dataGrid1.Sorting += DataGrid1_Sorting;  
  8.      };  
  9.   }  
  10.   
  11.   private void DataGrid1_Sorting(object sender, DataGridSortingEventArgs e)  
  12.   {  
  13.   }  
  14.   
  15.   private void Button_Click(object sender, RoutedEventArgs e)  
  16.   {            
  17.      DataGrid1_Sorting(dataGrid1, new DataGridSortingEventArgs(dataGrid1.Columns[0]));  
  18.   }  
But when I dont hide mu column header and click on it, it sorts column. Please help. 
Answers (2)