我正在vb.NET Visual Studio 2010中编写应用程序。我有一个数据存储在4列中的表(“index”,“description”,“value1”,“value2”)。
我将“description”列添加到listbox1中,我想在选择ListBox1的文本后,在自己的文本框中显示列“value1”和“value2”中的其他数据。
例如:如果我从ListBox1中选择“a”,我想为这个项目分配一个value1 = 5和value2 = 300,这个值应该出现在TextBox1和TextBox2中,当我选择“b”时,值7和400应该出现在这些文本框。但我不知道怎么做,所以我在寻求帮助。这是我的代码:
Public Class Form1
Dim dt2 As DataTable = New DataTable
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As
system.EventArgs) Handles MyBase.Load
Dim i As Integer
dt2.Columns.Add("index ", GetType(Integer))
dt2.Columns.Add("description", GetType(String))
dt2.Columns.Add("value1", GetType(Double))
dt2.Columns.Add("value2", GetType(Double))
dt2.Rows.Add(New Object() {1, "a", 5, 300})
dt2.Rows.Add(New Object() {2, "b", 7, 400})
dt2.Rows.Add(New Object() {3, "c", 8, 500})
dt2.Rows.Add(New Object() {4, "d", 9, 600})
If ListBox1.Text = "" Then
For i = 0 To 3
ListBox1.Items.Add(dt2.Rows(i).Item("description"))
AddHandler ListBox1.SelectedIndexChanged, AddressOf ListBox1_SelectedIndexChanged
TextBox2.Text = dt2.Rows(i).Item("value1")
Next
End If
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ListBox1.SelectedIndexChanged
For i = 0 To 3
TextBox2.Text = dt2.Rows.Item(i)("value1")
Next
End Sub
结束班
答案 0 :(得分:0)
试试这个。
If ListBox1.Text = ""
SelectedIndexChanged
中循环,最终会得到文本框中最后一个循环的值。使用列表框的选定索引获取所需的行。考虑使用数据绑定而不是将项目添加到ListBox(下面未演示)
Public Class Form1
Dim dt2 As DataTable = New DataTable
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As system.EventArgs) Handles MyBase.Load
AddHandler ListBox1.SelectedIndexChanged, AddressOf ListBox1_SelectedIndexChanged
Dim i As Integer
dt2.Columns.Add("index ", GetType(Integer))
dt2.Columns.Add("description", GetType(String))
dt2.Columns.Add("value1", GetType(Double))
dt2.Columns.Add("value2", GetType(Double))
dt2.Rows.Add(New Object() {1, "a", 5, 300})
dt2.Rows.Add(New Object() {2, "b", 7, 400})
dt2.Rows.Add(New Object() {3, "c", 8, 500})
dt2.Rows.Add(New Object() {4, "d", 9, 600})
ListBox1.Items.Clear()
For i = 0 To dt2.Rows.Count - 1
ListBox1.Items.Add(dt2.Rows(i).Item("description"))
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Text = dt2.Rows.Item(ListBox1.SelectedIndex)("value1")
TextBox2.Text = dt2.Rows.Item(ListBox1.SelectedIndex)("value2")
End Sub
End Class