简体   繁体   中英

How to chance column index on reordering column in DataGridView?

I'm importing some excel sheet to a DataGridView. I need to import, reorder the column in my project and then get the new indexes.

I have tried DataGridViewColumn.Index, DataGridViewColumn.DisplayIndex, Refresh(), but the index never changes.

How I can do this, please?

Thanks.

DataGridView Column Index is created when column is created. If you want to change the order in a GUI you change the DisplayIndex if you want to change the order int the DataGridView you either create a new DataGridView or put the column in a temporary list, remove all columns and add them again.

If you want to change the actual index of an element in you Data Source, you need to update your Data Source structure. but if you need to change the display position of a column, you can is DisplayIndex property. This is a sample to change the column index:

var items = new List<dynamic>
{
    new
    {
        Element1 = "Test Value",
        Id = 1
    },
    new
    {
        Element1 = "Test Value",
        Id = 1
    }
};
dataGridView1.DataSource = items;
dataGridView1.Columns[1].DisplayIndex = 0;
MessageBox.Show(dataGridView1[0, 0].Value.ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM