2016-03-26 70 views
-1

我該如何說,檢測列表框中的特定文本並將其替換爲特定文本。 如:c# - 替換列表框中的文本

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

你在談論的WinForms ListBox中? – Steve

回答

3

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

在WinForm的列表框,Text屬性包含當前所選項目的文本。
(我假設你有所有字符串項目)

如果你需要找到一個項目的文本,並改變它與不同的東西你只需要找到物品集合中的項目的索引,然後直接替換實際文字與新的一個。

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

還要注意,IndexOf返回-1,如果字符串是不存在的,所以沒有必要添加另一個檢查發現如果字符串列表或不