简体   繁体   中英

.Net Reorder DataGridView Columns at runtime

Is there a simple way to re-ordering the columns of a DataGridView that are bound to a DataSet at runtime?

I can do it simply via the DataGridView "Edit Columns" dialog at design time but have to remember to do this every time make changes to the form (remove or add the DataGridView to the form).

Thanks

Use DisplayIndex :

' Swap the last column with the first.'
Private Sub Button10_Click(ByVal sender As Object, _
    ByVal args As EventArgs) Handles Button10.Click

    Dim columnCollection As DataGridViewColumnCollection = _
        dataGridView.Columns

    Dim firstVisibleColumn As DataGridViewColumn = _
        columnCollection.GetFirstColumn(DataGridViewElementStates.Visible)
    Dim lastVisibleColumn As DataGridViewColumn = _
        columnCollection.GetLastColumn(DataGridViewElementStates.Visible, _
        Nothing)

    Dim firstColumn_sIndex As Integer = firstVisibleColumn.DisplayIndex
    firstVisibleColumn.DisplayIndex = _
        lastVisibleColumn.DisplayIndex
    lastVisibleColumn.DisplayIndex = firstColumn_sIndex
End Sub

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