2020/04/16(Thu) 01:57:12 編集(投稿者)
■No94503 (はる さん) に返信
標準では、ListBox のリスト部分に表示されるのは、Items コレクションの
要素を ToString() したものになります。
DisplayMember に要素の持つプロパティ名を指定すると、その値が
表示されます。
Imports VB = Microsoft.VisualBasic
Public Class Form1
Structure Item1
Public Property Value As String
Public Sub New(value As String)
Me.Value = value
End Sub
Public Overrides Function ToString() As String
Return VB.Right(Me.Value, 2)
End Function
End Structure
Structure Item2
Public Property Value As String
Public Sub New(value As String)
Me.Value = value
End Sub
Public ReadOnly Property Display
Get
Return VB.Right(Me.Value, 2)
End Get
End Property
End Structure
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dat(1) As String
dat(0) = "01234"
dat(1) = "56789"
With ListBox1
.Items.Clear()
For i = 0 To 1
.Items.Add(New Item1(dat(i)))
Next
End With
With ListBox2
.DisplayMember = "Display"
.Items.Clear()
For i = 0 To 1
.Items.Add(New Item2(dat(i)))
Next
End With
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
With ListBox1
If .SelectedIndex <> -1 Then
MsgBox(DirectCast(.Items(.SelectedIndex), Item1).Value)
End If
End With
End Sub
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
With ListBox2
If .SelectedIndex <> -1 Then
MsgBox(DirectCast(.Items(.SelectedIndex), Item2).Value)
End If
End With
End Sub
End Class