In a textChanged event for a textBox I am trying to do a search function for ListBoxItems like below.
It seems that I have done the code correct but no items is selected and when writing a string that is longer in length than the item that is shortest in length, I get Compileerror that says, Index must be less than the collection.

What could be wrong in this code ?

String GetString = TextBox1.Text.ToLower();
            String GetItemText = "";
            int GetLength = GetString.Length;
            

            for (int i = 0; i < eListBox2.Items.Count; i++)
            {
                if (eListBox2.Items[i].ToString().Length < GetLength)
                {
                    GetItemText = eListBox2.Items[i].ToString();
                    if (GetItemText.Substring(0, GetLength).ToLower() == GetString)
                    {
                        eListBox2.SelectedIndex = i;
                        break;
                    }
                }
            }

Recommended Answers

All 2 Replies

On the surface, it would appear you are referencing GetItemText.Substring(0, GetLength) in your loop, but GetLength might not be related to the length in GetItemText because your GetString above the loop is not directly tied. However, you didn't give what line produced the error, so can't be sure...

Yes, I forgot, the line that produced the error is this line:

if (GetItemText.Substring(0, GetLength).ToLower() == GetString)

I really cant get it where the error is as all code is running each time one will type a new letter in the textBox.

I do the check that:

if (eListBox2.Items[i].ToString().Length <= GetLength)

but anyway something is getting through here and get the compilerror that says this. I might have said wrong in above post"Index and length must refer to a location within the string."

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.