C# Combox使用 作者:马育民 • 2023-11-14 22:33 • 阅读:10048 # 添加项目 ``` 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:“此枚举数绑定到的列表已被修改。仅在列表没有更改时才能使用枚举数。” ``` # 清空 ``` fileLstBx.Items.Clear(); ``` # 删除选中的项目 ``` // 选中项的数量不为0时,就一直删除 while (fileLstBx.SelectedItems.Count > 0) { fileLstBx.Items.Remove(fileLstBx.SelectedItem); } ``` 原文出处:http://malaoshi.top/show_1IX6bGlv92jn.html