C# ListBox使用

选中模式

在vs属性中操作即可:

  • SelectionMode=none表示无法选中,
  • SelectionMode=one表示可选中一行,
  • SelectionMode=MultiSimple表示可选中多行,
  • SelectionMode=MultiExtended表示可选中多行且能用shift、ctrl来选择

添加项目

fileLstBx.Items.Add(fileName);

判断项目是否存在

fileLstBx.Items.Contains(fileName)

判断项目不存在就添加

if(!fileLstBx.Items.Contains(fileName)) {
    fileLstBx.Items.Add(fileName);
}

获取项目的总数

fileLstBx.Items.Count

遍历

方式一(推荐)

使用传统 for 语句遍历,麻烦啰嗦,但通用

for(int flbIndex = 0; flbIndex < fileLstBx.Items.Count; flbIndex++) 
{
    string file = fileLstBx.Items[flbIndex].ToString();
}

方式二

使用简单,但有些情况会报错

foreach (string file in fileLstBx.Items)

}

注意:使用该方式,不能操作 ListBox,如:设置选中、添加、删除等操作,会报错,如下:

System.InvalidOperationException:“此枚举数绑定到的列表已被修改。仅在列表没有更改时才能使用枚举数。”

设置选中

设置第一项选中

listBox.SelectedIndex= 0;

或

listBox.SetSelected(0, true);

获取选中的项

List<string> list = new List<string>();
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{       
    list.Add(listBox1.SelectedItems[i].ToString());
}

获取选中的索引

单选

listbox.SelectedIndex

多选

.SelectedIndices 返回集合,是选中的索引

foreach (int i in sheetListBox.SelectedIndices)
{

}

清空

fileLstBx.Items.Clear();

删除选中的项目

// 选中项的数量不为0时,就一直删除
while (fileLstBx.SelectedItems.Count > 0) {
    fileLstBx.Items.Remove(fileLstBx.SelectedItem);
}

遍历中删除指定的项

ListBox中的数据是文件列表,将不存在的文件移除

for (int i = this.fileLstBx.Items.Count - 1; i >= 0; i--)
{
    string item = fileLstBx.Items[i].ToString();
    if (!File.Exists(item))
    {
        fileLstBx.Items.Remove(item);
    }
}