You can handle the DataGridView.ColumnDisplayIndexChanged
event to prevent the user from changing the order of the first three frozen columns. In the event handler, check if the new display index of any of the first three columns is different from their initial positions. If it's different, set it back to the original position.
Here's the updated code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 1 To 9
DGV.Columns.Add("Column" & i.ToString.PadLeft(2, "0"c),
"Column" & i.ToString.PadLeft(2, "0"c))
Next
Dim values As List(Of Object)
For i As Integer = 1 To 100
values = New List(Of Object)
For j As Integer = 1 To 9
values.Add("Data" & i.ToString.PadLeft(5, "0"c) & "-" & j.ToString)
Next
DGV.Rows.Add(values.ToArray)
Next
DGV.AllowUserToOrderColumns = True
DGV.Columns(0).Frozen = True
DGV.Columns(1).Frozen = True
DGV.Columns(2).Frozen = True
' Handle the ColumnDisplayIndexChanged event
AddHandler DGV.ColumnDisplayIndexChanged, AddressOf DGV_ColumnDisplayIndexChanged
End Sub
Private Sub DGV_ColumnDisplayIndexChanged(sender As Object, e As DataGridViewColumnEventArgs)
' Check if any of the first three columns changed their display index
If e.Column.Index < 3 AndAlso e.Column.DisplayIndex <> e.Column.Index Then
' Set the display index back to the original position
e.Column.DisplayIndex = e.Column.Index
End If
End Sub
End Class
This code will prevent the user from changing the order of the first three frozen columns. They can still change the order of the remaining columns as needed.