views:

154

answers:

2

Is there a way to determine the order of the columns displayed in a datagridview when binding it to a datasource whitch contains an underlying IList ? I thought there was a specific property attribute for this purpose but can't recall what it actually was.

eg:

 public void BindToGrid(IList<CustomClass> list)
        {
            _bindingSource.DataSource = list;
            dataGridView1.DataSource = _bindingSource.DataSource;
        }

Type binded should be something like this

class CustomClass
{
        bool _selected = false;
        //[DisplayOrder(0)]
        public bool Selected
        {
            get { return _selected; }
            set { _selected = value; }
        }

        string _name;
         //[DisplayOrder(2)]
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        string _value;
         //[DisplayOrder(1)]
        public string Value
        {
            get { return _value; }
            set { _value = value; }
        }
}

Edit: I would like to add that I rather not want to add the columns manually to columns list in the designer. I'd like to keep this as dynamic as possible.

A: 

In the DataGridView specify an actual list of columns instead of allowing it to auto-databind. You can do this in Design View in Visual Studio by selecting the control and adding the columns. Make sure you specify in each column which property it should bind to. Then you can rearrange the columns any way you want as well as do other customizations.

I think that the DisplayOrder attribute is relatively new and probably not supported in the DataGridView control.

Eilon
A: 

The display order of the columns in the DataGridView is determined by the DisplayIndex properties of the DataGridViewColumn-s. You would have to set these properties on the columns of the grid, in order to change their order.

I also agree with Eilon's answer: you can create the list of the columns yourself, instead of auto-databinding, and that way you can determine the order in which they will be displayed.

treaschf
If you do try setting `DisplayIndex` be sure you set it after setting the `DataGridView`'s `DataSource`.
Ecyrb