1

How would I say, detect specific text in a listbox and replace it with specific text. Eg:

        private void timer1_Tick(object sender, EventArgs e)
    {
        if(listBox1.Text.Contains("Hi"))
        {
            // replace with Hello
        }
    }
1
  • Are you talking about Winforms ListBox? Commented Mar 26, 2016 at 15:21

2 Answers 2

5

In WinForms, you could do it like this:

if(listBox1.Items.Cast<string>().Contains("Hi")){ //check if the Items has "Hi" string, case each item to string
    int a = listBox1.Items.IndexOf("Hi"); //get the index of "Hi"
    listBox1.Items.RemoveAt(a); //remove the element
    listBox1.Items.Insert(a, "Hello"); //re-insert the replacement element
}
Sign up to request clarification or add additional context in comments.

Comments

4

In a WinForm ListBox, the Text property contains the text of the currently selected item.
(I assume that you have all string items)

If you need to find an item's text and change it with something different you need only to find the index of the item in the Items collection and then replace directly the actual text with the new one.

 int pos = listBox1.Items.IndexOf("Hi");
 if(pos != -1) listBox1.Items[pos] = "Hello";

Note also that IndexOf returns -1 if the string is not present, so no need to add another check to find if the string is in the list or not

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.