c# - Replace Text in ListBox

我们两清 提交于 2019-12-10 12:25:55

问题


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:


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
}



回答2:


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



来源:https://stackoverflow.com/questions/36236956/c-sharp-replace-text-in-listbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!