Can't sort datagrid content?

Nov 25, 2009 at 2:13 PM

Hello all.

I just started working with WPF. I installed the WPF Toolkit and am experimenting with the DataGrid. I got it to work fine displaying the result of a Linq query, accessing a data base, but the weird thing is that when I click on the headers, in order to sort the values, nothing happens. The columns are sort enabled and the arrow icon even changes direction, but the content doesn't change. Isn't the sorting done automatically, like the DataGrid in Windows Forms?

Thanks in advance.

Nov 30, 2009 at 12:18 PM

Sorry for insisting with this, but can't someone help me out with this?

Do I have to manually program the sort event of the data grid for it to work?

Thanks...

Nov 30, 2009 at 4:02 PM
Edited Nov 30, 2009 at 5:10 PM

I am not sure if this will fix your problem but you could try setting the canusersortcolumns attribute of the datagrid to true. Another thing is the sort wont work if you are using a datagridtemplatecolumn in place of the datagridtextColumn. Also the binding path element (like time period in the bottom example) should be a sortable datatype

 <toolkit:DataGrid AutoGenerateColumns="False" CanUserSortColumns="True">
     <toolkit:DataGrid.Columns>
          <toolkit:DataGridTextColumn Header="  Period  " Binding="{Binding Path= TimePeriod, ValidatesOnExceptions=True }" CanUserSort="True" 
IsReadOnly="True" Width="Auto" />
</toolkit:DataGrid.Columns>
</toolkit:DataGrid>
In case you are using a datagridTemplateColumn then you can mention the sortMemberPath
<toolkit:DataGridTemplateColumn Header="  Period  " CanUserSort="True" SortMemberPath="PeriodDate">
             <toolkit:DataGridTemplateColumn.CellTemplate>
                  <DataTemplate>
                      <TextBlock  Text="{Binding Path=PeriodDate, ValidatesOnExceptions=True, StringFormat = '{}{0:MMM yyyy}'}"  />
                  </DataTemplate>
            </toolkit:DataGridTemplateColumn.CellTemplate>
</toolkit:DataGridTemplateColumn>
Nov 30, 2009 at 4:51 PM

Did you specify SortMemberPath on your data grids column definition?

Nov 30, 2009 at 5:20 PM

thanks for the suggestions! The sorting still isn't working though...

I didn't specify the SortMemberPath, but when I look at the properties, I see that it has a default value with the same name as the Binding element. Should I change this?

Here's the code I'm using:

 

<toolkit:DataGrid AutoGenerateColumns="False" Margin="23,62,24,0" Name="dtgCities" 
CanUserDeleteRows
="False" CanUserReorderColumns="False" CanUserSortColumns="True"
IsReadOnly
="True" SelectionMode="Single" Height="230" VerticalAlignment="Top"> <toolkit:DataGrid.Background> <LinearGradientBrush SpreadMethod="Pad" StartPoint="0.5,0" EndPoint="0.5,1"> <GradientStop Color="GhostWhite" Offset="0"/> <GradientStop Color="Gray" Offset="8"/> </LinearGradientBrush> </toolkit:DataGrid.Background> <toolkit:DataGrid.Columns> <toolkit:DataGridTextColumn Header="City" MinWidth="200" Binding="{Binding Name}" CanUserSort="True" IsReadOnly="True" /> <toolkit:DataGridTextColumn Header="Status" MinWidth="200" Binding="{Binding Status}" CanUserSort="True" IsReadOnly="True" /> </toolkit:DataGrid.Columns> </toolkit:DataGrid>

And the code for data binding:

 

 

var list = from City city in context.Cities
where city.stateCode == stateCode
  orderby city.Name select city; dtgCities.ItemsSource = list;

 

 

Nov 30, 2009 at 5:28 PM

Once again not sure if this is the solution but try using the 'City' class as the reference type for the list variable instead f just using 'var'. I think the issue might be because the datagrid does not know the datatype for the Name variable and is thus not able to sort the entries

Nov 30, 2009 at 5:37 PM
paladugu457 wrote:

Once again not sure if this is the solution but try using the 'City' class as the reference type for the list variable instead f just using 'var'. I think the issue might be because the datagrid does not know the datatype for the Name variable and is thus not able to sort the entries

hmmm... ok, I'm going to try this.... but how do I use a list to retrieve the result of a Linq query? Because when I try:

List<City> cityList = select ...

I get a variable type exception...

Sorry for the begginer's question, but I also just started experimenting with Linq...

 

Nov 30, 2009 at 6:00 PM

I was assuming you have a City class with getters and setters to each of the tables varaibles. In your example  'context' is the linq datacontext you are using so I am guessing you should use something similar to this

List<MyDBClass.MyTable> metricList = (from temp in newDC.MyTable
                                                       where <your condition>
                                                       select temp).ToList();

 Here newDC is teh datacontext i.e object of the MyDBClass class and the MyDBClass class has a definition of the MyTable like this 

 

public partial class MyTable : INotifyPropertyChanging, INotifyPropertyChanged
	{
		
		private string _Name;
		
		private int _content;
		
		.......
       }

 

Also i noticed you used List<City>. I think it should be List<Cities> where Cities is the class that you created to represent the table contents. 

 

 

Dec 1, 2009 at 1:55 PM

As suggested, I changed the generic "var" for a List variable and the sorting now works!

Thanks for all the help!

Jan 4, 2010 at 11:00 PM

Hi, just continuing on this thread on WPF_DataGrid sorting with another question. I am using linq 2 entities.

If I do the following, sorting does not work, but binding the grid, in place editing, deleting and inserting works fine, automatic committing back to the DB using model.SaveChanges(); model.AcceptAllChanges(); works 100%.
IEnumerable<Customer> pc =
from customers in servicesModel.Customer
select customers;
uiDgCustomers.ItemsSource = pc;

If I do the following, sorting does work, binding the grid, in place editing, deleting and inserting works fine, automatic committing back to the DB using model.SaveChanges(); model.AcceptAllChanges(); does not work. 

List<Customer> pc =
(from customers in servicesModel.Customer
select customers).ToList();
uiDgCustomers.ItemsSource = pc;

 

 How do I get the sorting, binding, updating, deleting, inserting and the linq model commits back to the database working 100% without copious code? Happy to share my solution if that will help?

Thanks

 

Jan 5, 2010 at 9:37 AM

Hi, I believe I have the cure for my problem - this seems to do the trick.  Note the red it should always just be that, it. Not sure why, but this works 100% now.

        private void uiDgCustomers_Sorting(object sender, Microsoft.Windows.Controls.DataGridSortingEventArgs e)
        {
            if (!isCurrentOrderAscending)
            {
                isCurrentOrderAscending = true;
                uiDgCustomers.ItemsSource = servicesModel.Customer.OrderBy("it.[" + e.Column.SortMemberPath + "] ASC");
                e.Column.SortDirection = System.ComponentModel.ListSortDirection.Ascending;
            }
            else
            {
                isCurrentOrderAscending = false;
                uiDgCustomers.ItemsSource = servicesModel.Customer.OrderBy("it.[" + e.Column.SortMemberPath + "] DESC");
                e.Column.SortDirection = System.ComponentModel.ListSortDirection.Descending;
            }
        }