c# - Replace Text in ListBox

2019-06-14 16:27发布

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

标签: c# listbox
2条回答
ら.Afraid
2楼-- · 2019-06-14 17:04

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

查看更多
萌系小妹纸
3楼-- · 2019-06-14 17:23

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
}
查看更多
登录 后发表回答