简体   繁体   English

如何对DataGridView中的重新排序列进行排序?

[英]How to chance column index on reordering column in DataGridView?

I'm importing some excel sheet to a DataGridView. 我正在将一些Excel工作表导入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. 我已经尝试过DataGridViewColumn.Index,DataGridViewColumn.DisplayIndex,Refresh(),但是索引永远不会改变。

How I can do this, please? 请问我该怎么做?

Thanks. 谢谢。

DataGridView Column Index is created when column is created. 创建列时将创建DataGridView列索引。 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. 如果要在GUI中更改顺序,则要更改DisplayIndex,如果要更改DataGridView中的顺序,则可以创建新的DataGridView或将列放在临时列表中,然后删除所有列并再次添加。

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. 但是如果需要更改列的显示位置,则可以使用DisplayIndex属性。 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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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