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

时间:2014-12-12 16:03:38

标签: vb.net winforms textbox listbox

我尝试使用这样的代码:

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

表单看起来像这样:

enter image description here

我需要在用户在文本框中输入时更改该列表文本。是否有可能在运行时这样做?

2 个答案:

答案 0 :(得分:4)

您正在使用表单的离开事件MyBase.Leave,因此当它触发时,对您来说没用。

尝试使用TextBox的TextChanged事件。

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
                                 Handles TextBox1.TextChanged

确保检查列表框中是否实际选择了某个项目:

If ListBox1.SelectedIndex > -1 Then
  ListBox1.Items(ListBox1.SelectedIndex) = TextBox1.Text
End If

答案 1 :(得分:1)

使用双击选择列表框内的行(项目)并更改或修改。 而不是使用文本框使用lapply事件

ListBox1_MouseDoubleClick

然后在此事件中添加此代码

Private Sub ListBox1_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDoubleClick

OR

Dim intIndex As Integer = ListBox1.Items.IndexOf(ListBox1.SelectedItem)
Dim objInputBox As Object = InputBox("Change Item :","Edit", ListBox1.SelectedItem)
If Not objInputBox = Nothing Then
    ListBox1.Items.Remove(ListBox1.SelectedItem)
    ListBox1.Items.Insert(intIndex, objInputBox)
End If