# C# & .Net 2.0: Column Order Problems on DataGridView using a BindingList<T> as DS



## Guy (Feb 19, 1999)

I am having problems getting the column order in a DataGridView object to display how I want it. Here are my objects:

Data object

```
class CData
{
//data members
private uint id;
private string name;
private object otherstuff;
//constructor
... //standard
//get / set
public uint ID{
get{ return id; }
set{ id = value; }
}
... //basic get/set for the other data members
}
```
I then create multiple CData objects and place them in a List<CData> object "myList". When I go to bind this list to a DataGridView I use the following code

```
BindingList<CData> bindlist = new BindingList<CData>(myList);
myDataGridView.DataSource = bindlist;
myDataGridView.Refresh()
```
the problem comes when my form is shown and my data is presented. Currently I can not figure out how to order the columns generated from my CData class properties. By default I thought they would show up in the order that they are declared like:

| ID | Name | OtherData |

but I find that the order is chosen at random (or some other factor I can not figure out) and they display something like:

| OtherData | ID | Name |

Now normally this wouldnt be too big of a problem but in my real world application I am using a Data object with over 100 fields which are generated from a file with a strict structure layout and it is critical that I see my columns in the proper order.

I hope I explained this properly and would appreciate any help that can be offered on the matter.

Thank you.


----------



## Gayatri (Jul 30, 2007)

I had the same problem and resolved using a Custom Attribute.
Create a Custom Attribute class DiplayIndex

[AttributeUsage(AttributeTargets.Property, AllowMultiple=true)]
public class DisplayIndexAttribute : Attribute
{
private int index;
public DisplayIndexAttribute(int index)
{
this.index = index;
}

public int Index
{
get { return this.index; }
}
}

Specify the DisplayIndex on your class property
[DisplayIndex(0)]
public uint ID{
get{ return id; }
set{ id = value; }
}
[DisplayIndex(1)]
public string Name
{
get; set;
}
[DisplayIndex(2)]
public string OtherData
{
get; set;
}

And write the following code in your Form load event to set the DisplayIndex

foreach (PropertyInfo property in typeof(CData).GetProperties())
{
DisplayIndexAttribute displayIndex = Attribute.GetCustomAttribute(property, typeof(DisplayIndexAttribute)) as DisplayIndexAttribute;
if (displayIndex != null)
{
if (_dataGridView.Columns.Contains(property.Name))
_dataGridView.Columns[property.Name].DisplayIndex = displayIndex.Index;
}
}


----------

