C# Combox使用 作者:马育民 • 2023-11-14 22:33 • 阅读:10064 # 添加项目 ``` fileLstBx.Items.Add(fileName); ``` # 获取选中的值 ``` startHourCB.Text ``` # 判断项目是否存在 ``` fileLstBx.Items.Contains(fileName) ``` ### 判断项目不存在就添加 ``` if(!fileLstBx.Items.Contains(fileName)) { fileLstBx.Items.Add(fileName); } ``` # 获取项目的总数 ``` fileLstBx.Items.Count ``` # 设置选中 ### 方式一: 指定索引 ``` startHourCB.SelectedIndex= 0; ``` ### 索引二: 指定值 ``` Combobox.SelectText = “默认选中文本”; ``` 但是如果Combobox的DropDowStyle属性,选择为DropDownList则上面的方法就不能用了 用下面的方法比较好用 ``` Combobox.SelectedIndex = Combobox.Items.IndexOf(“默认选中文本”); ``` https://blog.csdn.net/easyboot/article/details/68062196 # 遍历 ### 方式一(推荐) 使用传统 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://www.malaoshi.top/show_1IX6bGlv92jn.html