2010-11-24 54 views
0

我有一個類正在從文本文件中的逗號分隔行填充。VB.NET:來自一個類的字段

我想讓每個對象的名稱屬性出現在列表框中,然後讓所選對象的其餘屬性顯示在文本框中。如何將所選對象的屬性加載到正確的文本框?

+0

什麼是每個對象的類型?如何將文本文件內容映射到這種類型的對象上? – cdhowie 2010-11-24 21:58:09

回答

0

我假設您填寫的類有對象的列表,並且你已經找到了如何填寫列表框...

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged 

    For Each obj As YourObjectType In YourClass.CollectionOfYourObjects 

     If obj.Name = ListBox1.SelectedItem.ToString Then 

      Textbox1.Text = obj.Property1 
      Textbox2.Text = obj.Property2 

     End If 

    Next 

End Sub 
0

你必須爲每個屬性和了一個TextBox的屬性數量是靜態的,不是嗎? 您必須將DisplayMember設置爲您想要在列表框中看到的屬性名稱。

這種簡化的樣品應該工作:

Public Class ListBox 
    Private Sub ListBox_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
     Dim allFoos As New List(Of FooClass) 
     For i As Int32 = 1 To 10 
      Dim foo As New FooClass 
      foo.Name = "Foo_" & i 
      foo.Prop1 = "Prop1_" & i 
      foo.Prop2 = "Prop2_" & i 
      foo.Prop3 = "Prop3_" & i 
      allFoos.Add(foo) 
     Next 
     Me.ListBox1.DataSource = allFoos 
     Me.ListBox1.DisplayMember = "Name" 
    End Sub 

    Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged 
     Dim foo As FooClass = DirectCast(ListBox1.SelectedItem, FooClass) 
     Me.TxtName.Text = foo.Name 
     Me.TxtProp1.Text = foo.Prop1.ToString 
     Me.TxtProp2.Text = foo.Prop2.ToString 
     Me.TxtProp3.Text = foo.Prop3.ToString 
    End Sub 
End Class 

Class FooClass 
    Private _name As String 
    Private _prop1 As Object 
    Private _prop2 As Object 
    Private _prop3 As Object 

    Public Property Name() As String 
     Get 
      Return _name 
     End Get 
     Set(ByVal value As String) 
      _name = value 
     End Set 
    End Property 
    Public Property Prop1() As Object 
     Get 
      Return _prop1 
     End Get 
     Set(ByVal value As Object) 
      _prop1 = value 
     End Set 
    End Property 
    Public Property Prop2() As Object 
     Get 
      Return _prop2 
     End Get 
     Set(ByVal value As Object) 
      _prop2 = value 
     End Set 
    End Property 
    Public Property Prop3() As Object 
     Get 
      Return _prop3 
     End Get 
     Set(ByVal value As Object) 
      _prop3 = value 
     End Set 
    End Property 
End Class 
相關問題