Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

vb.net - Find a part of text in a listbox

I've been given some code to find text that is contained in a listbox but, its not what I need. When the user types in the textbox (which is the search field), they have to type the exact text, not the part of the text. Is there any way to find a part of a value/text in a listbox?

For example, I have a listbox that contains these items:

  1. data1
  2. data2

When I type (2) in the search field(textbox/richtextbox), I would like the second item, which contain the '2' value, to be selected.

How can I code this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use IndexOf

Dim hits = From item In listBox1.Items.Cast(Of String)()
           Where item.IndexOf(txtSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0
If hits.Any Then
    listBox1.SelectedItem = hits.First()
End If

If you don't want to ignore the case, just use String.Contains instead of String.IndexOf.

Note that above is a linq query, so it won't work with .NET 2 this way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...