You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为WinForm ComboBox添加并读取索引ID

.NET 4.0 WinForm ComboBox绑定ID与名称并获取选中ID的解决方案

1. 绑定包含ID和名称的数据源

你已经通过LINQ得到了包含UserLevelCategoryId(索引ID)和LevelCategoryName(显示名称)的匿名类型列表,直接将这个列表绑定到ComboBox即可,无需转成字符串数组:

// 获取包含ID和名称的去重列表
var distinctPermissions = permissions.GroupBy(_ => _.LevelCategoryName)
                                    .Select(_ => _.First())
                                    .Select(_ => new { _.UserLevelCategoryId, _.LevelCategoryName })
                                    .ToList();

// 绑定到ComboBox
SystemAComboBox.DisplayMember = "LevelCategoryName"; // 设置下拉框显示的文本字段
SystemAComboBox.ValueMember = "UserLevelCategoryId"; // 设置对应的值ID字段
SystemAComboBox.DataSource = distinctPermissions;    // 设置数据源

2. 获取选中项的ID

绑定完成后,直接通过SelectedValue属性获取对应的ID,无需处理字符串:

// 获取选中的ID(根据实际类型转换,比如int)
int selectedId = Convert.ToInt32(SystemAComboBox.SelectedValue);

如果需要验证是否有选中项,可以先判断:

if (SystemAComboBox.SelectedValue != null)
{
    int selectedId = Convert.ToInt32(SystemAComboBox.SelectedValue);
    // 后续业务处理
}

替代方案:直接操作SelectedItem(匿名类型)

如果不想用SelectedValue,也可以将SelectedItem强转为dynamic类型获取ID(.NET 4.0支持dynamic):

dynamic selectedItem = SystemAComboBox.SelectedItem;
int selectedId = selectedItem.UserLevelCategoryId;

内容的提问来源于stack exchange,提问作者K.Z

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:45:34