簡體   English   中英

替換列表框中的文本

[英]c# - Replace Text in ListBox

我怎么說,要檢測列表框中的特定文本並將其替換為特定文本。 例如:

        private void timer1_Tick(object sender, EventArgs e)
    {
        if(listBox1.Text.Contains("Hi"))
        {
            // replace with Hello
        }
    }

WinForms ,您可以這樣操作:

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
}

在WinForm ListBox中,Text屬性包含當前所選項目的文本。
(我假設您具有所有字符串項)

如果需要查找項目的文本並將其更改為其他內容,則只需在Items集合中找到該項目的索引,然后將實際文本直接替換為新的文本即可。

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

還要注意,如果字符串不存在,IndexOf返回-1,因此無需添加其他檢查以查找字符串是否在列表中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM