1

I am binding a Gridview to a custom object. But the order of fields displayed is not correct. Is there any way to set the fields display order when binding a Gridview to a custom object?

Thanks in advance.

ramu
  • 1,019
  • 3
  • 15
  • 41

3 Answers3

0

If your speaking about ASP.NET grid view then you have to turn off AutoGenerate Columns then Add columns manually with the order you want.

Ahmed Magdy
  • 5,956
  • 8
  • 43
  • 75
  • hi Pr0fess0rX,i am implementing ICustomTypeDescriptor also in my custom data object.But the displayed fields are not in correct sequence. – ramu Mar 08 '11 at 12:29
0

It is not even guaranteed that the order is the same as the declaration order of the properties in your custom object as MS exposes:

"The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies."

You should order it by yourself for example with Array.Sort. Here are some further informations and also an example on hot to ensure that it's ordered by declaration: http://www.sebastienmahe.com/v3/seb.blog/2010/03/08/c-reflection-getproperties-kept-in-declaration-order/ With Linq its even simplier:

type.GetProperties().OrderBy(x=>x.MetadataToken)

To order your custom object it needs to implement IComparable or you have to provide an IComparer as parameter for the Sort-Function.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Hi Tim Schmelter,i implemented IEnumerator,IEnumerable,ICustomTypeDescriptor interfaces.Sorting is the next priority but i am expecting a way to set the display order of the fields. – ramu Mar 08 '11 at 12:27
  • @Ramu: it's always possible to add TemplateField or BoundFields to the GridView-Columns collection by yourself. You only have to set `AutogenerateColumns=false`. Here is an example: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.autogeneratecolumns.aspx – Tim Schmelter Mar 08 '11 at 12:29
-1

I am sorry the link I found before was wrong. Thank you for the comments. I recognized that when GridView.AutoGenerateColumns is set to true you can change the order of the columns in the datasource. If AutoGenerateColumns is false, you can change your columns when you build and bind the grid from the code. For example,

DataTable dt = new DataTable();
dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(string));

dt.Rows.Add(new object[] { obj1.property1, obj2.property2 });
//...

Grid1.DataSource = dt;
Grid2.DataBind();
MUG4N
  • 19,377
  • 11
  • 56
  • 83