简体   繁体   中英

c# - Replace Text in ListBox

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
        }
    }

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM