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

如何将DataGridView中的数据填充到CheckedListBox中?

解决CheckedListBox填充数据问题

你的问题出在直接将DataGridViewCell对象添加到CheckedListBox,而不是单元格里的实际数据值。下面分场景给出解决方案:

场景1:单元格存储单个权限值

如果row.Cells[3]里是单个权限字符串(比如"管理员权限"),用以下代码:

// 获取单元格值,处理null避免空引用
string rightValue = row.Cells[3].Value?.ToString() ?? string.Empty;

// 清空现有项(按需选择)
chklbRolesRoleRights.Items.Clear();

// 添加权限并设置选中
int itemIndex = chklbRolesRoleRights.Items.Add(rightValue);
chklbRolesRoleRights.SetItemChecked(itemIndex, true);

场景2:单元格存储多个权限(如逗号分隔)

如果单元格里是用分隔符(逗号、分号等)分隔的多权限字符串(比如"查看,编辑,删除"),先分割再添加:

string rightsValue = row.Cells[3].Value?.ToString() ?? string.Empty;
chklbRolesRoleRights.Items.Clear();

// 分割字符串为单个权限列表
string[] rightsList = rightsValue.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

foreach (string right in rightsList)
{
    // 添加并选中每个权限
    int index = chklbRolesRoleRights.Items.Add(right.Trim());
    chklbRolesRoleRights.SetItemChecked(index, true);
}

场景3:CheckedListBox已有预设选项

如果CheckedListBox已经提前添加了所有可选权限,只需根据单元格值匹配并设置选中状态:

string rightsValue = row.Cells[3].Value?.ToString() ?? string.Empty;
List<string> selectedRights = rightsValue.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(r => r.Trim())
                                        .ToList();

// 遍历预设选项,匹配则选中
for (int i = 0; i < chklbRolesRoleRights.Items.Count; i++)
{
    string itemText = chklbRolesRoleRights.Items[i].ToString();
    chklbRolesRoleRights.SetItemChecked(i, selectedRights.Contains(itemText));
}

关键注意点

  • 一定要获取row.Cells[3].Value.ToString(),而非直接添加row.Cells[3](后者添加的是Cell对象,显示的是类型信息而非数据)
  • 用?.ToString() ?? string.Empty处理null值,防止空引用异常

内容的提问来源于stack exchange,提问作者Yoki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 13:10:07