如何查找ListBox中所选项目的数量

本文关键字:选项 项目 ListBox 何查找 查找 | 更新日期: 2024-05-25 12:30:09

我正试图找出用户单击按钮时选择了多少项。

以下是我尝试过的:

private void button1_Click(object sender, EventArgs e)
{
    ListItem li;
    int x = 0;
    foreach ( li in listBox1.Items) 
    {
        if (li.Selected == true)
        {
            x++;
        }
    }
}

但它反而给了我一个错误。

Type and identifier are both required in a foreach statement

此外,在Windows窗体应用程序中是否有一种特定的方法可以计算列表框中的项目数量?

如何查找ListBox中所选项目的数量

ListBox类中有一个方法可以获取所选项目的数量:

int numberSelectedItems = listBox1.SelectedItems.Count;

这将为您提供所选项目的列表。检查计数属性istBox1.SelectedItems.count以获取所选项目的列表。

var selectedItems = listBox1.SelectedItems;

您可以使用SelectedIndicesSelectedItems来获得所选项目的计数,如以下

listBox1.SelectedIndices.Count

listBox1.SelectedIndices.Count

和CCD_ 5以获得列表框中的项目数量

ListBox1.Items.Count

在您的Foreach中,您需要指定Type,请尝试低于

int x = 0;
foreach(ListItem item in ListBox1.Items)
{
    if (item.Selected) 
       x++;
}