如何在c#中使用for测试从列表框中删除的项目数量

时间:2017-04-19 01:26:56

标签: c#

If ((textbox1.text - textbox2.text)==100 ||(textbox1.text - text2.text)==250)
{
   For (long i= textbox2.text;i < textbox1.text ;i++)
   {
           Listbox.remove (i)//listbox contain serials 
           // how can test how many items had been deleted form the listbox
   }
}

2 个答案:

答案 0 :(得分:0)

在我开始回答之前,我假设您在问题中包含的代码如下:

If ((textbox1.text - textbox2.text)==100 ||(textbox1.text - text2.text)==250)
{
    For (Int i= textbox2.text;i < textbox1.text ;i++)
    {
        Listbox.remove (i)//listbox contain serials
        // how can test how many items had been deleted form the listbox
    }
}

如果您正在使用标准列表框,则从中删除项目的正确语法是:Listbox.Items.Remove(item) docs

此外,您无法在算术运算中使用textbox.text,您需要先使用Convert.Toint32将字符串转换为整数

要计算受影响项目的数量,只需在删除它们之前检查它们是否存在,然后创建一个计数器变量:

int tb1 = Convert.ToInt32(textbox1.text);
int tb2 = Convert.ToInt32(textbox2.text);
if ((tb1 - tb2)==100 ||(tb1 - tb2)==250)
{
    int counter=0;
    for (long i= tb2;i < tb1;i++)
    {
        if (Listbox.Items.Contains(i)) {
            counter++;
            Listbox.Items.Remove(i);
        }
    }
}
Console.WriteLine(counter + " items were removed");

答案 1 :(得分:0)

您可以添加&#34;计数器&#34;在你正在进行删除的循环中。

示例:

      int counter = 0;

      //say, this is your loop for deletion of items on listbox
      for (int i=0; i<5; i++)
      {
          //if condition for deletion was met
          counter++;
      }

      //you can call counter after the loop, this will be the number of deleted items from your listbox