开发者

Rearranged columns in C#

开发者 https://www.devze.com 2023-01-01 07:41 出处:网络
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.AutoGene

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 sa开发者_JS百科me 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


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);
            }
        }
    }


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号