2013-01-08 74 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