需要帮助按订单历史记录的日期排序ListView项目

时间:2017-03-06 11:35:42

标签: vb.net vb.net-2010

这就是订单历史的样子:

This is how the Order History looks like.

我想要做的是按日期对此ListView中的项目进行排序。

到目前为止,我找不到任何有用的资源材料,我可以按日期对项目进行排序。

Private Sub frmOrderHistory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim orders As String = WindowsApplication1.Class1.Orders
    Dim arrCheck(3) As String
    Dim lineNum As Integer = -1
    For Each i As String In System.IO.Directory.GetFiles(orders)
        Dim a, c As String
        a = System.IO.Path.GetFileNameWithoutExtension(i)
        c = System.IO.Path.GetFullPath(i)
        For Each line As String In File.ReadLines(c)
            lineNum = lineNum + 1
            ListView1.Items.Add(a)
            arrCheck = Split(line, ",")
            ListView1.Items(lineNum).SubItems.Add(arrCheck(0))
            ListView1.Items(lineNum).SubItems.Add(arrCheck(1))
        Next

    Next
End Sub

1 个答案:

答案 0 :(得分:0)

您的问题的解决方案是创建要在列表视图中显示的对象列表,根据要求对列表视图进行排序,然后将排序列表用于列表视图中的显示。

我建议创建一个类Order来从文件中收集订单详细信息。创建订单列表并对列表进行排序,然后在列表视图中显示如下。

以下是课程Order

Public Class Order
Public Property OrderDate() As DateTime
Get
    Return m_OrderDate
End Get
Set
    m_OrderDate = Value
End Set
    End Property
Private m_OrderDate As DateTime

Public Property Item() As String
Get
    Return m_Item
End Get
Set
    m_Item = Value
End Set
End Property
Private m_Item As String

Public Property Price() As Double
Get
    Return m_Price
End Get
Set
    m_Price = Value
End Set
End Property
Private m_Price As Double
End Class

以下是列表绑定的代码。

Private Sub frmOrderHistory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim orders As String = WindowsApplication1.Class1.Orders
    Dim arrCheck(3) As String
    Dim orderList = New List(Of Order)()
For Each filePath As var In System.IO.Directory.GetFiles(orders)
    Dim order = New Order()
    order.OrderDate = DateTime.ParseExact(System.IO.Path.GetFileNameWithoutExtension(filePath), "dd-MM-yyyy", CultureInfo.InvariantCulture)
    For Each line As var In System.IO.File.ReadAllLines(filePath)
    arrCheck = line.Split(New Char() {","C})
    order.Item = arrCheck(0)
    order.Price = Convert.ToDouble(arrCheck(1))
    orderList.Add(order)
        Next
Next

Dim sortedOrder = orderList.OrderByDescending(Function([or]) [or].OrderDate).ToList()

    For i As var = 0 To sortedOrder.Count - 1
        listView1.Items.Add(sortedOrder(i).OrderDate.ToString("dd-MM-yyyy"))
        listView1.Items(i).SubItems.Add(sortedOrder(i).Item)
        listView1.Items(i).SubItems.Add(sortedOrder(i).Price.ToString("00.00"))
    Next
End Sub

正如你可以观察到的那样,这个解决方案并不是直截了当的。它需要将字符串格式化为日期时间并返回字符串。双值相同。还需要不止一次循环项目。

更简单的方法是使用datagridview。如果使用datagridview,只需单击几下即可设置列的列和数据格式。并且您可以直接将订单集合绑定到它,而无需通过以下集合循环。

DataGridView1.DataSource = sortedOrder;