Reputation: 81528
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
Upvotes: 2
Views: 1992
Reputation: 53593
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);
}
}
}
Upvotes: 3
Reputation: 31610
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
Upvotes: 0
Reputation: 19765
How are you selecting? SELECT *? You need to specify the columns in the order you want them.
Upvotes: 0