有时简单的代码会让我们感到很困惑。我在过去的几个小时里在互联网上研究过这个问题。
我有一个列表框,数据将从Access表加载。当我在列表框中选择一个项目时,我想在文本框中显示该项目。
我已尝试过如下代码,但对我来说没有任何作用:
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
For i As Integer = 0 To listBox1.SelectedItems.Count - 1
textBox1.Text &= DirectCast(listBox1.SelectedItems(i), DataRowView)(1).ToString & vbCrLf
Next
End Sub
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
textBox1.Text = listBox1.SelectedItem.Value
End Sub
以下是从访问表
为列表框提供值的代码Dim dataAdapter As New OleDbDataAdapter("select * from eval", connection)
Dim ds As DataSet = New DataSet
dataAdapter.Fill(ds, "eval")
listBox1.DataSource = ds
listBox1.DisplayMember = "eval"
listBox1.ValueMember = "eval.eval"
答案 0 :(得分:2)
以下是您可以执行的操作的简单示例。假设您有一个包含4个项目的列表框:VB.Net,C#,Java和Python。首先,制作列表框SelectionMode = MultiSimple
。如果我理解正确,您希望列表框中已选中的所有项目都转移到文本框。你可以通过编写这段代码来做到这一点:
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Clear()
For Each Item As Object In ListBox1.SelectedItems
TextBox1.AppendText(Item.ToString + Environment.NewLine)
Next
End Sub
以下是结果: (抱歉质量不好)
答案 1 :(得分:1)
listBox1.SelectedItem会返回一个System.Data.Datarow,因为那是你放在那里的东西。如果要在列表框显示的文本框中显示相同的文本,只需使用:
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
textBox1.Text = listBox1.text
End Sub
如果你想要一个来自另一个领域的值(你没有显示你的字段,所以我们假装有一个名为" FirstName")你可以这样做:
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
Dim DR as datarow = listBox1.SelectedItem
textBox1.Text = DR("FirstName")
End Sub
答案 2 :(得分:1)
textbox1.Text = listBox1.GetItemText(listBox1.SelectedItem);