【问题标题】:Add object to listbox and use different string representations depending on the listbox?将对象添加到列表框并根据列表框使用不同的字符串表示形式?
【发布时间】:2012-06-30 14:55:39
【问题描述】:

我有几个具有相同对象类型的列表框,我遇到的问题是我不希望在所有列表框中使用相同的 ToString() 方法显示对象。有没有办法解决这个问题?

目前我将字符串添加到列表框,然后我使用选定的字符串在对象列表中搜索正确的对象,但我根本不喜欢那个解决方案。

【问题讨论】:

    标签: vb.net object listbox tostring


    【解决方案1】:

    假设有一个这样的员工类:

    Public Class Employee
        Public Property ID As Integer
        Public Property FirstText As String
        Public Property SecondText As String
        ' and go on with other properties
        ....
    End Class
    

    现在,当您填充列表框时,您将列表框的 DisplayMember 和 ValueMember 设置为 Employee 的两个不同属性

    Dim myList As ArrayList = New ArrayList()
    myList.Add(New Employee() With {.ID = 1, .FirstText = "John Doe", .SecondText = "Doe John"})
    myList.Add(New Employee() With {.ID = 2, .FirstText = "Mark Ross", .SecondText = "Ross Mark"})
    
    ListBox1.DataSource = myList
    ListBox2.DataSource = myList
    
    ListBox1.ValueMember = "ID"
    ListBox1.DisplayMember = "FirstText"
    
    ListBox2.ValueMember = "ID"
    ListBox2.DisplayMember = "SecondText"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      相关资源
      最近更新 更多