CheckedBoxComboBox选中项拼接结果异常,如何正确获取并拼接所有选中项?
问题原因
你当前代码的问题是额外引入了一层不必要的for (int j = 0; j < x; j++)内层循环,每识别到一个选中项时,就会循环x次(x为当前累计选中项个数)拼接当前项,最终导致输出内容重复。
修正方案
方案1:适配原有逻辑的写法
和你之前使用CheckListBox的处理逻辑保持一致,仅删除多余的内层循环即可:
objNPTBEL.workdayidlist = null; // 先筛选出所有选中的选项 var checkedItems = checkBoxComboBox1.CheckBoxItems .Where(item => item.CheckState == CheckState.Checked) .ToList(); for (int x = 0; x < checkedItems.Count; x++) { if (x < checkedItems.Count - 1) objNPTBEL.workdayidlist += checkBoxComboBox1.GetItemText(checkedItems[x].Text) + ","; else objNPTBEL.workdayidlist += checkBoxComboBox1.GetItemText(checkedItems[x].Text); }
方案2:更简洁的写法
直接使用.NET内置的string.Join方法处理逗号拼接,无需手动判断分隔符,代码更简洁也不易出错:
var checkedItemTexts = checkBoxComboBox1.CheckBoxItems .Where(item => item.CheckState == CheckState.Checked) .Select(item => checkBoxComboBox1.GetItemText(item.Text)); objNPTBEL.workdayidlist = string.Join(",", checkedItemTexts);
内容的提问来源于stack exchange,提问作者user12366709
相关产品推荐
相关产品推荐

