Probably it's very easy, but I have searched for a post or somehone who have the same problem without fortune. I have a Listbox in Vb Net, which contains a list of names. in vb6, while typing in the listbox the selected item changed automatically based on the letters typed until completion, but I can't find a method that repeats the same thing in VS, as the only thing it lets me do is identify only the first one letter typed in the listbox. So, if in the list there are two similar names like Autocarro or Automobile, if after the 'A' I type the 'U' the cursor moves to the 'U' of 'Urban'. Could anyone help me find a solution whithout using a textbox? Thanks in advance
CodePudding user response:
You can use a ComboBox
with the DropDownStyle
set to Simple
. This displays a TextBox
combined with a ListBox
(hence the name Combo Box).
To make it select entries automatically you can add a TextChanged
event handler with the following code:
private void ComboBox1_TextChanged(object sender, EventArgs e)
{
int inputLength = comboBox1.Text.Length;
if (inputLength > 0) {
int index = comboBox1.FindString(comboBox1.Text);
if (index >= 0) {
comboBox1.SelectedIndex = index;
comboBox1.Focus();
comboBox1.SelectionStart = inputLength;
comboBox1.SelectionLength =
((string)comboBox1.Items[index]).Length - inputLength;
}
}
}
Note, however, that editing the text box part becomes a bit difficult as the selection mechanism kicks in every time you edit the text. E.g. deleting text with Dellete or Backspace does not work well, as the automatic selection restores the text immediately. You can delete the whole text by typing Ctrl-A, Delete.
ComboBox
after having typed "cl"
:
CodePudding user response:
Try this (Works both for text box and combobox, not sure if it works directly in list box, you can try in this lime), what you can do is add textbox on top of list box and run second code to add data to textbox as suggestion
ComboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
Or this one
Dim iddata As New AutoCompleteStringCollection()
Dim idtable As New DataTable
idtable = (your datatable source)
For Each r As DataRow In idtable.Rows
iddata.Add(r("id").ToString)
Next
With Textbox1
.AutoCompleteCustomSource = iddata
.AutoCompleteMode = AutoCompleteMode.Suggest
.AutoCompleteSource = AutoCompleteSource.CustomSource
End With