简体   繁体   中英

DataGridView get current column index

I have a DataGridView that can have its columns reordered by the user, what I need to obtain is the current order index of each column, but iterating over them before and after moving the columns shows the same order so it looks as if the index never changes:

for (int i = 0; i < dsgDataGrid.Columns.Count; i++)
{
    MessageBox.Show(dsgDataGrid.Columns[i].Name);
}

Is there a property I can use which shows the current order of the column?

Is there a property i can use which shows the current order of the column?

Sure there is - DataGridViewColumn.DisplayIndex

Unlike the Index property, the DisplayIndex property corresponds to the current position of the column as displayed by the user interface (UI). By default, each column's DisplayIndex is set to numbers of increasing order, which reflects the order in which they were added. The Visible property value does not affect the DisplayIndex value. To determine the display position of a column based on its visibility or other state, use the GetFirstColumn, GetLastColumn, or GetNextColumn method of the DataGridViewColumnCollection class.

Every column in the control has a unique DisplayIndex value. The values start with 0 and proceed in numerical order without skipping any values. When you change the DisplayIndex value for a column, the DisplayIndex values for other columns are changed to reflect the new order.

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