我的程序有一个文本框和一个列表视图。在列表视图中,我添加了三个人的名字,John,Kat,Adel。
如何在列表视图中选择John的名字时,John的年龄会自动显示在文本框中?
当在列表视图中选择Kat的名字时,Kat的年龄会自动显示在文本框中吗?
同样也是Adel。
任何帮助将不胜感激! 非常感谢你!
答案 0 :(得分:1)
你应该在列表框的 SelectedIndexChanged 事件中编写代码
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
' John, Kat, Adel
SELECT CASE ListBox1.Text.Tolower.Trim
CASE "john"
TextBox1.Text = "15" ' - the age you want to display
CASE "kat"
TextBox1.Text = "16"
CASE "adel"
TextBox1.Text = "17"
END SELECT
End Sub
<强>更新强>
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
' John, Kat, Adel
TextBox1.Text = ListBox1.SelectedIndex.ToString
End Sub
答案 1 :(得分:1)
我通常不会这样做 - 所以请不要滥用帮助。我仍然认为您应该花更多时间在MSDN.com上阅读这些信息。对于刚接触VB.Net开发的人来说,此链接是一个很好的资源:http://msdn.microsoft.com/en-us/vstudio/hh388568
我是针对3.0框架编写的,这与我在Visual Studio 2010中为Windows Mobile 6.5开发一样接近。其中一些功能可能无法在您的应用程序中运行,但它应该传达基本的想法。 / p>
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Here we create a new generic list of our User class with some preloaded items.
Dim users As New List(Of User) From {New User("John", 15), New User("Kat", 16), New User("Adel", 17)}
' Here we will add another user at after the list has already been created.
users.Add(New User("Bob", "18"))
' Set the DataSource of the listbox to our users
Me.ListBox1.DataSource = users
' Set the DisplayMember to the Name property of the User so the list will show the names of the users.
Me.ListBox1.DisplayMember = "Name"
End Sub
' This event is fired when a different item in the listbox is selected
' This event will fire when the ListBox is bound to a datasource.
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
' If there is an item selected (i.e. the index is not -1)
If ListBox1.SelectedIndex <> -1 Then
' Create a temporary variable to store the currently selected item (which is a user)
' We could have used CType instead to avoid this variable
Dim selectedUser As User = ListBox1.SelectedItem
' Set the textbox text to the User class's age.
TextBox1.Text = selectedUser.Age
Else
' If we are here then it means no item is selected in the listbox.
' Empty the textbox.
TextBox1.Text = ""
End If
End Sub
End Class
' Create a User class with a Name and Age propery.
Class User
Public Property Name As String
Public Property Age As Integer
' Create a constructor that accepts a Name (string) and an Age (integer)
Public Sub New(ByVal _name As String, ByVal _age As Integer)
Me.Name = _name
Me.Age = _age
End Sub
End Class
答案 2 :(得分:0)
在更改listview值时添加一个回调函数,在此函数中检查选择了哪个值,即John,Kat或Adel,然后在文本框中设置适当的年龄。