开发者

finding a solution for find string in listbox

I has 4 item on my form......... tow listbox ,one button and one text box I has a listbox 'A' with many items..... i need a item in a listbox 'B' from listbox 'A' steps are as follow.....that i like to performe...........

1)enter a word or character in a textbox 2)press a button 3)the list appear in listbox 'B'.......that is character or string start in listbox 'A' that is we write in textbox (for matching)

i need a help in which a item that can be in listbox 'B' is getting for listbox 'A' that is Starting string or character we ente开发者_运维问答r in the text box. please try to solve me out..........


Not quite sure I follow. Using the text box' Changed event would be a good trigger instead of a button. Just iterate the list items and check for a match with String.StartsWith. For example:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    ListBox2.Items.Clear()
    If TextBox1.Text.Length > 0 Then
        For index As Integer = 0 To ListBox1.Items.Count - 1
            Dim txt = ListBox1.Items(index).ToString()
            If txt.StartsWith(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase) Then
                ListBox2.Items.Add(txt)
            End If
        Next
    End If
End Sub


I don't have an IDE in front of me, and it's been a while since I've done WinForms development, so I may not have the exact event name or other stuff, but you get the idea. This also means my code will be in C# since I'm more familiar with that, but you should be able to find the VB equivalent.

You'll want to bind to the proper event on the text box first. Maybe the KeyPress or KeyUp event? Or TextChanged? You want one that fires any time text changes in the text box. In that event, you'll loop through the items in listbox A and compare their values to the text in the text box. Basic string comparison is all that's needed, if there's a .StartsWith() or something of that nature, otherwise some basic use of .Substring() will do fine (based on the length of the string in the text box).

The loop would likely be something along the lines of:

listboxA.Items.ForEach(i =>
    {if (i.StartsWith(textboxA.Text)) listboxB.Items.Add(i);});

Or...

foreach (var i in listboxA.Items)
    if (i.StartsWith(textBoxA.Text))
        listboxB.Items.Add(i);

Like I said, this is all off the top of my head, so the code may not be exact. But hopefully you get the idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜