Thursday, September 27, 2012

WPF Datagrid (Prevent DataGrid last row from being sorted on column header clicked!)

Here's the WPF version of prevent total rows from being sorted.
Images:
1. Form Load, no column header is clicked (unsorted records)

2. Name header is clicked (sorting by column). The names are sorted alphabetically.

Below are the methods used:
Code:
      /// <summary>  
      /// column header clicked(sorting)  
      /// </summary>  
      private void dgProducts_Sorting(object sender, DataGridSortingEventArgs e)  
      {  
        DataRowView rv = (DataRowView)dgProducts.Items[dgProducts.Items.Count - 1];  
        if (rv[0].ToString().Contains("Total:"))  
        {  
          dvCopy = dgProducts.Items.SourceCollection as DataView;  
          rv.Delete();  
        }  
        sorted_aborted = e.Handled;  
      }  

      /// <summary>  
      /// layout is updated  
      /// </summary>  
      private void dgProducts_LayoutUpdated(object sender, EventArgs e)  
      {  
        if (!sorted_aborted)  
        {          
          //method to add totals computation  
          ShowProductSorted();  
          sorted_aborted = true;  
        }  
        else  
        {  
          DisableLastRow();  
        }  
      }    

      /// <summary>  
      /// show sorted products  
      /// </summary>  
      private void ShowProductSorted()  
      {  
        Total = 0;  
        DataTable dt = new DataTable();  
        dt = dvCopy.ToTable();  
        dvCopy = null;  
        dgProducts.ItemsSource = null;  
        foreach (DataRow row in dt.Rows)  
        {  
          Total = Total + Convert.ToDouble(row[1].ToString());  
        }  
        DataRow dr1 = dt.NewRow();  
        dr1[1] = Total;  
        dt.Rows.Add(dr1);  
        yourdatagrid.ItemsSource = dt.AsDataView();        
      }  

0 comments:

Post a Comment