I am working with VB 2005 express edition and I have a listview control on a form with 2 buttons. I want to allow the user to be able to reorder columns to suit their needs. I have no problems with this. I also want them to be able to remove columns or re-add columns based on their wishes. My problem is if a column is added, after the user changes the position, the data gets added to the wrong column.
Any ideas on how to do this properly? The code below illustrates what I am taking about.
Any ideas on how to do this properly? The code below illustrates what I am taking about.
Code:
Public Class Form1
Private myColumns(6) As ColumnHeader ' Used for creating column headers.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Make sure that the view is set to show details.
ListView1.View = View.Details
ListView1.AllowColumnReorder = True
ListView1.GridLines = True
' Create some column headers for the data.
myColumns(0) = New ColumnHeader()
myColumns(0).Text = "Column 1"
myColumns(1) = New ColumnHeader()
myColumns(1).Text = "Column 2"
myColumns(2) = New ColumnHeader()
myColumns(2).Text = "Column 3"
myColumns(3) = New ColumnHeader()
myColumns(3).Text = "Column 4"
myColumns(4) = New ColumnHeader()
myColumns(4).Text = "Column 5"
myColumns(5) = New ColumnHeader()
myColumns(5).Text = "Column 6"
myColumns(6) = New ColumnHeader()
myColumns(6).Text = "Column 7"
Me.ListView1.Columns.AddRange(myColumns)
' Loop through and size each column header to fit the column header text.
ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
AddRow()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ListView1.Columns.Remove(myColumns(3))
ListView1.Columns.Remove(myColumns(0))
ListView1.Columns.Insert(3, myColumns(3))
End Sub
Private Sub AddRow()
Dim row As ListViewItem
Dim subText_Col(5) As ListViewItem.ListViewSubItem
row = New ListViewItem("Col 1")
subText_Col(0) = New ListViewItem.ListViewSubItem(row, "Col 2")
subText_Col(1) = New ListViewItem.ListViewSubItem(row, "Col 3")
subText_Col(2) = New ListViewItem.ListViewSubItem(row, "Col 4")
subText_Col(3) = New ListViewItem.ListViewSubItem(row, "Col 5")
subText_Col(4) = New ListViewItem.ListViewSubItem(row, "Col 6")
subText_Col(5) = New ListViewItem.ListViewSubItem(row, "Col 7")
row.SubItems.AddRange(subText_Col)
ListView1.Items.Add(row)
End Sub
End Class