0
votes

I'm trying to select listbox item if contains a specific string. Here is my code:

string SearchDomain="youdial.in";
for (int i = 0; i < ListBox2.Items.Count; i++)
            {
                var UrlList = new Uri(ListBox2.Items[i].ToString());
                var UrlList = UrlList.Host;
                if (UrlList == SearchDomain)
                {
                    ListBox2.SelectedIndex = i;
                    urllbl.Text = ListBox2.SelectedItem.ToString();
                    return;
                }
            }

enter image description here

If ListBox2 have more than 1 matched results than above code select last matched item, but i want to select first matched item. e.g if Query match with 3rd, 7th and 9th item, I want to get the value of 3rd item. Thanks in Advance, sorry for my bad English.

2
As an aside, this code will throw an exception if there is no matching element as you're doing i <= ListBox2.Items.Count. you're lucky it didn't do so before. you're looking for i < ListBox2.Items.Count - Ousmane D.
as for "If ListBox2 have more than 1 matched results than above code select last matched item" . I don't see how that's possible as you're iterating sequentially from the first index to the last. - Ousmane D.
Again, your code doesn't even compile as you cannot compare a type URI and a string like this --> if (UrlList == SearchDomain). - Ousmane D.
#Aomine I don't know how is this possible, My question updated with output image. - Narender Godara

2 Answers

0
votes

Just change return; to break; Break statement will stop the for loop from executing further.

string SearchDomain="youdial.in";
for (int i = 0; i < ListBox2.Items.Count; i++)
            {
                var UrlList = new Uri(ListBox2.Items[i].ToString());
                var UrlList = UrlList.Host;
                if (UrlList == SearchDomain)
                {
                    ListBox2.SelectedIndex = i;
                    urllbl.Text = ListBox2.SelectedItem.ToString();
                    break;
                }
            }
0
votes

Just reverse the counter change the

for (int i = 0; i < ListBox2.Items.Count; i++)

to

for (int i = ListBox2.Count-1 ; i > -1 ; i--)