views:

48

answers:

3

How can I get the rearranged columns out of a datagridview in C#? I need to get all the columns currently being displayed in order. I can get the default columns order by setting datagridview.AutoGenerateColumns=false but I get the same old order even after I've rearranged the columns in my table.

Edit: Basically what I need is to be able to iterate through all the columns of a datagridview based on their display index

Thanks

A: 

How are you selecting? SELECT *? You need to specify the columns in the order you want them.

n8wrl
A: 

Have you rearranged their order in the ItemTemplate section of your grid? You can also change the order via the context menu for a GridView, alternative you can change your SQL statement and make sure autogenerate is off

RandomNoob
+1  A: 

Use the DisplayIndex property of your DataGridView Columns.

The DisplayIndex property:

Gets or sets the display order of the column relative to the currently displayed columns.

Edit:
It's ugly, and I'm sure people are going to point and laugh, but this might give you a rough idea on one implementation to improve upon.

Create a DGV with three columns and set their DisplayName properties like so:

    dataGridView1.Columns[0].DisplayIndex = 1;
    dataGridView1.Columns[1].DisplayIndex = 2;
    dataGridView1.Columns[2].DisplayIndex = 0;

Add the following code to loop through all the columns access the columns in the DGV in their DisplayIndex order:

    for (int index = 0; index < dataGridView1.Columns.Count; index++) {
        foreach (DataGridViewColumn c in dataGridView1.Columns) {
            if (c.DisplayIndex == index) {
                // You've got your next column.
                Console.WriteLine(c.Name);
            }
        }
    }
Jay Riggs
Ok. But how can I iterate through all the columns based on the display index property?
chown
Could optimize it slightly by breaking once you've found the next column.
SwDevMan81
I'm also thinking something similar to yours 'rough' solutions but it looks that we will skip some columns if we implemented this way.
chown
This way should be ok. If you want other suggestions you could keep a dictionary<int,int> of the display index as the key, and the actual index as the value, then you iterate over the keys and use dataGridView1.Columns[value] to go in display order (since value would give you the actual index for the display index)
SwDevMan81