Title | Keep track of ListView columns when the user reorders them in Visual Basic .NET |
Description | This example shows how to keep track of ListView columns when the user reorders them in Visual Basic .NET. The program catches the ListView's ColumnReordered event and updates collections that keep track of the original column indexes and headers. |
Keywords | ListView, reorder, columns, VB.NET, Visual Basic .NET |
Categories | Controls, VB.NET |
|
|
If you allow the user reorder a ListView's columns, the underlying data source is not modified. The display changes but the columns of data don't.
As far as I know (correct me if I'm wrong), the ListView doesn't provide a way to tell which column is where after they are rearranged. This example keeps track of the original column indexes and titles. It stores them in two collections:
|
|
Private m_ColumnIndexes As Collection
Private m_ColumnNames As Collection
|
|
When the program starts, it initializes these collections.
|
|
' Record the initial column names.
m_ColumnNames = New Collection()
For i As Integer = 0 To lvwBooks.Columns.Count - 1
m_ColumnNames.Add(lvwBooks.Columns(i).Text)
Next i
' Record the initial column indexes.
m_ColumnIndexes = New Collection()
For i As Integer = 0 To lvwBooks.Columns.Count - 1
m_ColumnIndexes.Add(i)
Next i
|
|
When the user reorders columns, the program catches the ListView's ColumnReordered event and updates the collections so it knows where the columns have moved.
|
|
' Update the column order.
Private Sub lvwBooks_ColumnReordered(ByVal sender As _
System.Object, ByVal e As _
System.Windows.Forms.ColumnReorderedEventArgs) Handles _
lvwBooks.ColumnReordered
Dim column_name As String = _
CStr(m_ColumnNames(e.OldDisplayIndex + 1))
m_ColumnNames.Remove(e.OldDisplayIndex + 1)
m_ColumnNames.Add(column_name, _
Before:=e.NewDisplayIndex + 1)
Dim index As Integer = _
CInt(m_ColumnIndexes(e.OldDisplayIndex + 1))
m_ColumnIndexes.Remove(e.OldDisplayIndex + 1)
m_ColumnIndexes.Add(index, Before:=e.NewDisplayIndex + _
1)
' Display the current name order.
For i As Integer = 1 To m_ColumnIndexes.Count
Debug.Write(CStr(m_ColumnNames(i)) & " ")
Next i
Debug.WriteLine("")
' Display the current index order.
For i As Integer = 1 To m_ColumnIndexes.Count
Debug.Write(CInt(m_ColumnIndexes(i)) & " ")
Next i
Debug.WriteLine("")
End Sub
|
|
|
|