如何在运行时更改列表框中的选定项文本?

Mas*_*gol 5 vb.net textbox listbox winforms

我试过这样的代码:

Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles MyBase.Leave
  ' This way is not working
  ListBox1.SelectedItem = TextBox1.Text
  ' This is not working too
  ListBox1.Items(ListBox1.SelectedIndex) = TextBox1.Text
End Sub
Run Code Online (Sandbox Code Playgroud)

表格如下所示:

在此处输入图片说明

当用户在文本框中键入时,我需要更改该列表文本。可以在运行时做到这一点吗?

Lar*_*ech 5

您正在使用表单的 leave 事件MyBase.Leave,因此当它触发时,它对您毫无用处。

尝试改用 TextBox 的 TextChanged 事件。

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
                                 Handles TextBox1.TextChanged
Run Code Online (Sandbox Code Playgroud)

确保检查是否在 ListBox 中实际选择了一个项目:

If ListBox1.SelectedIndex > -1 Then
  ListBox1.Items(ListBox1.SelectedIndex) = TextBox1.Text
End If
Run Code Online (Sandbox Code Playgroud)