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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27447474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:06:37  来源:igfitidea点击:

How to change selected item text in list box at run time?

vb.netwinformstextboxlistbox

提问by Mas Bagol

I tried with code like this:

我试过这样的代码:

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

The form is looked like this:

表格如下所示:

enter image description here

在此处输入图片说明

I need to change that list text while user typing in the text box. Is it possible to do that at run time?

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

采纳答案by LarsTech

You are using the form's leave event MyBase.Leave, so when it fires, it is useless to you.

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

Try using the TextChanged event of the TextBox instead.

尝试改用 TextBox 的 TextChanged 事件。

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

Make sure to check if an item is actually selected in the ListBox:

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

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

回答by hollopost

Use Double click to select line (item) inside list box and change or modify. Instead of using text box use ListBox1_MouseDoubleClickevent

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

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

then add this code inside this event

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

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

OR

或者

Dim objInputBox As Object = InputBox("Change Item :","Edit", ListBox1.SelectedItem)
If Not objInputBox = Nothing Then
   ListBox1.Items(ListBox1.SelectedIndex) = objInputBox 
End If