none
[VB 2010] ListBox 的選取問題(可能跟 Data Binding 有關) RRS feed

  • 問題

  • 我個VB Program 的 UI 有 SrcListBox(ListBox) , DestListBox(ListBox) , ShowFareLabel(Label)

    不知怎麼的,當我選取其中一個 ListBox 的選項時,另一個 ListBox 也選取了相同的選項,使  ShowFareLabel.Text 永遠是

    The source and the destination are the same.

    Please select another station.

    可以讓兩個 ListBox 選取兩個不同的選項嗎?

    問題跟 Data Binding 有關嗎?

    謝謝~

    程式碼如下:

    Public Class MainForm

        Private Class Station

            Dim _LongName As String
            Dim _ShortName As String
            Dim _Location As UInteger

            Sub New(LongName As String, ShortName As String, Location As UInteger)
                _LongName = LongName
                _ShortName = ShortName
                _Location = Location
            End Sub

            ReadOnly Property LongName As String
                Get
                    Return _LongName
                End Get
            End Property

            ReadOnly Property ShortName As String
                Get
                    Return _ShortName
                End Get
            End Property

            ReadOnly Property Location As Integer
                Get
                    Return _Location
                End Get
            End Property

        End Class

        Private StationList As New ArrayList() From {
                New Station("Sheung Shui", "SS", 1),
                New Station("Fanling", "FL", 2),
                New Station("Tai Wo", "TW", 3),
                New Station("Tai Po Market", "TPM", 4)
            }

        Private SrcStation As Station
        Private DestStation As Station

        Private Sub MainForm_Load() Handles Me.Load
            DataBinding(SrcListBox)
            DataBinding(DestListBox)
        End Sub

        Private Sub DataBinding(Target As ListBox)
            With Target
                .DataSource = StationList
                .DisplayMember = "LongName"
                .ValueMember = "ShortName"
                .ClearSelected()
            End With
            AddHandler Target.SelectedValueChanged, AddressOf Target_SelectedValueChanged
        End Sub

        Private Sub Target_SelectedValueChanged(sender As Object, e As EventArgs)
            If SrcListBox.SelectedIndex <> -1 AndAlso DestListBox.SelectedIndex <> -1 Then

                SrcStation = SrcListBox.SelectedItem
                DestStation = DestListBox.SelectedItem

                Dim Distance As UInteger = Math.Abs(SrcStation.Location - DestStation.Location)
                Select Case Distance
                    Case 0
                        ShowFareLabel.Text = "The source and the destination are the same." & vbCrLf & "Please select another station."
                    Case Else
                        ShowFareLabel.Text = Format("The fare needed is ${0}.", Distance * 10)
                End Select
            End If
        End Sub

    End Class

                
    2012年9月8日 上午 10:09

解答

所有回覆