如何获取ASP ListBox中启用且选中的复选框项
筛选ListBox中选中且启用的项并拼接值
核心需求是遍历ListBox时,跳过禁用(Enabled=false)和未选中(Selected=false)的ListItem,最终将符合条件的项的Value拼接为逗号分隔的字符串。
简洁实现(LINQ方式)
用LINQ可以大幅简化代码,无需手动处理循环和拼接逻辑:
var selectedEnabledItems = lstbx_formname.Items.Cast<ListItem>() .Where(item => item.Enabled && item.Selected) .Select(item => item.Value); string hh = string.Join(",", selectedEnabledItems);
循环方式优化版
如果偏好传统循环写法,可以合并判断条件,减少代码嵌套,提升可读性:
string hh = string.Empty; for (int i = 0; i < lstbx_formname.Items.Count; i++) { ListItem currentItem = lstbx_formname.Items[i]; // 同时判断启用和选中状态,满足才执行拼接 if (currentItem.Enabled && currentItem.Selected) { hh = string.IsNullOrEmpty(hh) ? currentItem.Value : $"{hh},{currentItem.Value}"; } }
优化说明
- 合并
Enabled和Selected的判断条件,避免多层嵌套,逻辑更直观; - 使用
string.IsNullOrEmpty()替代直接判断hh == "",能兼容hh为null的场景,更严谨; - LINQ写法利用内置的
string.Join()自动处理逗号拼接,无需手动判断空字符串,代码更简洁。
内容的提问来源于stack exchange,提问作者Harsh Kadam VSS
相关产品推荐
相关产品推荐

