Tuesday 1 February 2011

How to order columns while binding to Grid?

One of my silverlight newbie friend asked, when I have a collection of data that I bind to grid and want to autogenerate columns based on the class it is bound to but I want to control the order it appear and also I do not want to display some of the columns. It was funny when he asked me I was stumped since I never did this kind of binding. Well, it is not that difficult. ComponentModel is here to help. So here is how we do it.

1. Create you XAML which which will have nothing but a Grid like the following

   1:  <sdk:DataGrid Name="_normal" AutoGenerateColumns="True" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0">
   2:  </sdk:DataGrid>  
2. Create your model. In my case I created a person class. 
public class Person: IDataErrorInfo
{
[StringLength(20)]
[Display(Description="Name", Order=1)]
public string Name { get; set; }

[Range(0, 100)]
[Display(Description="Age", Order=2)]
public int Age { get; set; }

[Display(Description="Address 1", Order=5)]
public string Address1 { get; set; }

[Display(Description = "Address 2", Order = 4)]
public string Address2 { get; set; }

[Display(Description="Amounts", Order=3)]
public double Amount {get; set; }

[Display(AutoGenerateField=false)]
public double DoNotShowThisField {get; set; }

private double doNotShowThisField1;
}

Now you create your data collection and bind it to your gird. Your output would be something like the following

image

The attribute, Display sets the column order to display in the grid. As you can see Amount comes last in the class property but the Display order was set to 3 so it appears at 3rd column. Also notice DoNotShowThisField, even though it is declared as public, the display attribute says, when autogenerate fields for data binding, do not include this field.

Hope this helps.

0 comments:

Post a Comment