2013-01-08 72 views
0

我試圖從列表框中刪除特定的項目,但是我收到了轉換錯誤。 它似乎不喜歡我已經將ListBox中的項目稱爲string項目的事實。無法將ListItem類型的對象轉換爲字符串

if (CheckBox1.Checked == true) 
     { 
      foreach (string item in ListBox1.Items) 
      { 
       WebService1 ws = new WebService1(); 
       int flag = ws.callFlags(10, item); 

       if (flag == 1) 
       { 
        ListBox1.Items.Remove(item); 
       } 
      } 
     } 

錯誤 -

Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to type 'System.String'. 

我怎樣才能解決這個問題?

編輯

我的問題是,當我更改爲(ListItem item in ListBox1.Items)方法(我試過)行 - int flag = ws.callFlags(10, item);符,因爲Web服務正在接收string明確。這就給出了錯誤 -

Error 2 Argument 2: cannot convert from 'System.Web.UI.WebControls.ListItem' to 'string' 
Error 1 The best overloaded method match for 'testFrontEnd.WebService1.callFlags(int, string)' has some invalid arguments 
+0

使用'ListItem'而不是'string'。 –

+0

請參閱編輯,因爲我已經試圖實現這一點,問題是Web服務需要一個字符串。 – Ebikeneser

回答

2

你遍歷ListItems,所以你應該做的:

foreach(ListItem item in ListBox1.Items){ 
    WebService1 ws = new WebService1(); 
    int flag = ws.callFlags(10, item.Text); // <- Changed to item.Text from item 

    if (flag == 1) 
    { 
     ListBox1.Items.Remove(item); // <- You'll have an issue with the remove 
    } 
} 

你也要去當您嘗試RemoveListBoxItem得到一個錯誤,因爲你不能從刪除您正在迭代的Enumerable。天真地,您可以將您的foreach環路切換到for環路來解決該問題。

此代碼應該可以刪除以及修復「無法投射」錯誤。

for(int i = 0; i < ListBox1.Items.Count; i++) 
{ 
    ListItem item = ListBox1.Items[i]; 
    WebService1 ws = new WebService1(); 
    int flag = ws.callFlags(10, item.Text); 

    if (flag == 1) 
    { 
     ListBox1.Items.Remove(item); 
    } 
} 

最後的筆記;您的WebService1似乎是一個自定義類,它可能是一個好主意,讓它實現IDisposable接口並將其包裝在using子句中,以便確保在使用後妥善處理它。

public class WebService1 : IDisposable { // ... 

using (WebService1 ws = new WebService1()) 
{ 
    // Code from inside your for loop here 
} 
+0

這似乎非常接近,是一個非常好thoght出答案但是由於某種原因,大約一半的清單是清除?即使爲了調試的目的,我已經設置在數據庫中只有兩條記錄爲'-1',所以應該在列表框中留下2條記錄?如果我能夠使它正常工作,我會將其標記爲正確的,但是現在結果很奇怪 – Ebikeneser

+0

好吧我只是我意識到,如果我按下一次,其中一半刪除,我不檢查,然後再檢查另一半,如果我最終重複這個問題,我會回到兩個保留'-1'行!所以它是一種工作,但是你有什麼想法爲什麼我需要反覆推它,直到所有不需要的值都消失了嗎?! – Ebikeneser

+0

@Jambo如果不知道'callFlags'方法的作用,很難告訴你什麼是錯的。既然你檢查返回的值是否爲'1'('if(flag == 1)'),你將刪除每個調用'callFlags'返回'1'的項。也許你想檢查它不等於'-1'?類似於('if(flag!= -1)')。 – NominSim

2

更改刪除是:

ListBox1.Items.Remove(ListBox1.Items.FindByName(item)); 
+0

打我吧:( – Chazt3n

+0

這不是OP的問題... – NominSim

0

ListBox1.Items返回ListItem對象的集合。您希望item的類型爲ListItem,然後使用item.Text或可能的item.Value