Programmatically move columns in the .NET WinForms DataGrid

Columns in a DataGrid appear in the order that their ColumnStyles were added to the TableStyle being used by the grid. To change this order you must create a new TableStyle and add the ColumnStyles in the desired order as this illustrates.

    Public Sub MoveColumn(theDataGrid As DataGrid, theMappingName As String, _
                          theOldColumn As Integer, theNewColumn As Integer)  	

        If theOldColumn = theNewColumn Then Return  	

        Dim oldTS As DataGridTableStyle = theDataGrid.TableStyles(theMappingName)  	
        Dim newTS As New DataGridTableStyle()  	
        Dim i As Integer = 0

        newTS.MappingName = theMappingName	

        While i < oldTS.GridColumnStyles.Count  	
            If i <> theOldColumn And theOldColumn < theNewColumn Then  	
                newTS.GridColumnStyles.Add(oldTS.GridColumnStyles(i))  	
            End If  	

            If i = theNewColumn Then  	
                newTS.GridColumnStyles.Add(oldTS.GridColumnStyles(theOldColumn))  	
            End If  	

            If i <> theOldColumn And theOldColumn > theNewColumn Then  	
                newTS.GridColumnStyles.Add(oldTS.GridColumnStyles(i))  	
            End If  	

            i += 1  	
        End While  	

        theDataGrid.TableStyles.Remove(oldTS)  	
        theDataGrid.TableStyles.Add(newTS)  	
    End Sub 	

    '
    ' Sample call:  	
    '
    MoveColumn(myDataGrid, "Customers", 3, 1)  	




About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page