单击列标题

时间:2014-02-05 03:29:31

标签: vb.net winforms listview

我想按listview的时间或者我现在使用的付款或名称combobox订购商品,但我想点击listview标题时这样做在标题栏上我希望listview按其排序,我在组合框中使用此代码请帮帮我。

enter image description here

Private Sub OrderBy()
    Try
        Dim OB As String
        If ComboBox1.Text = "ID" Then
            OB = "ID"
        ElseIf ComboBox1.Text = "Name" Then
            OB = "StudentName"
        ElseIf ComboBox1.Text = "Payment" Then
            OB = "Payment"
        ElseIf ComboBox1.Text = "Time" Then
            OB = "LessonTime"
        ElseIf ComboBox1.Text = "Date" Then
            OB = "LessonDate"
        End If

        Dim dt As New DataTable
        Dim ds As New DataSet
        ds.Tables.Add(dt)
        Dim da As New OleDbDataAdapter("select * from Tend order by " & OB & "", con)
        da.Fill(dt)
        Dim myrow As DataRow
        For Each myrow In dt.Rows
            ListView1.Items.Add(myrow.Item(0))
            ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(1))
            ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(2))
            ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(3))
            ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(4))
            ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(5))
        Next

2 个答案:

答案 0 :(得分:0)

更好地解释,使用ColumnClick事件并使用e.Column来了解所点击列的索引

编辑:这不是最好的方法,但现在对你来说这是最简单的方法。

Private Sub OrderBy(Col as Integer)
Try
    Dim OB As String

    Select Case Col
       'Depending on the order of columns in your table
       Case 0
          OB = "ID"
       Case 1
          OB = "StudentName"
       Case 2
          OB  = "Payment"
       Case 3
          OB  = "LessonTime"
       Case 4
          OB  = "LessonDate"
    End Select

    Dim dt As New DataTable
    Dim ds As New DataSet
    ds.Tables.Add(dt)
    Dim da As New OleDbDataAdapter("select * from Tend order by " & OB & "", con)
    da.Fill(dt)
    ListView1.Items.Clear
    For Each myrow As DataRow In dt.Rows
        Dim item = ListView1.Items.Add(myrow.Item(0))
        item.SubItems.Add(myrow.Item(1))
        item.SubItems.Add(myrow.Item(2))
        item.SubItems.Add(myrow.Item(3))
        item.SubItems.Add(myrow.Item(4))
        item.SubItems.Add(myrow.Item(5))
    Next
End Try
End Sub

Private Sub ColumnClick(ByVal o As Object, ByVal e As ColumnClickEventArgs) Handles ListView1.ColumnClick
    OrderBy(e.Column)
End Sub 

答案 1 :(得分:0)

我遇到了同样的问题,我在c#中找到了一个Microsoft教程,并在一段时间后转换为VB.NET。

您可以在http://www.sourcecodester.com/visual-basic-net/5415/how-sort-listview-control-column-header-vbnet.html

上查看我转换的开源项目

它显示了如何添加新项目,分成列,并且您可以通过单击列标题对列表视图进行排序。您还可以设置默认排序方法。