Search Amazon:

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)  	
Sign In
  User Id 
  Password 


Submit Your Own Code and Articles




About TheScarms
About TheScarms

Ask me your programming questions

I read every email and answer all I can.

User Feedback: Be the first to add a comment! Items to Show:     

     
You must log in to post feedback.
Comment:    
 

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

Email this page


TheScarms AppSentinel lets you securely copy protect and create evaluation versions of your software

TheScarms(tm) AppSentinel lets you quickly and easily create evaluation versions of your software and stop unauthorized copying and unregistered use of your programs!

Get your free
trial copy today!


      The World's Number 1 Web Host

© Copyright 2008 TheScarms