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

DataGridView中CheckBox列赋值为true后仍未显示勾选状态如何解决

问题解决方案
  • 第一步:为新增的复选框列设置默认值,避免空值导致状态不生效
    在IniciarGV方法插入复选框列的代码块中添加默认值配置:
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "Seleccione";
checkBoxColumn.Width = 50;
checkBoxColumn.Name = "checkBoxColumn";
checkBoxColumn.DefaultValue = false; // 新增这行
gvPermisos.Columns.Insert(0, checkBoxColumn);
  • 第二步:修改复选框赋值逻辑,强制编辑状态提交生效
    调整原有遍历赋值代码,增加编辑状态控制,同时跳过未使用的新行避免报错,还优化了遍历效率:
var permisoIdSet = new HashSet<decimal>(TraerPermisos.Select(p => p.IDPANTALLA));
foreach (DataGridViewRow row in gvPermisos.Rows)
{
    if (row.IsNewRow) continue;
    var pantallaId = decimal.Parse(row.Cells["idPantalla"].Value?.ToString() ?? "0");
    gvPermisos.CurrentCell = row.Cells["checkBoxColumn"];
    gvPermisos.BeginEdit(true);
    row.Cells["checkBoxColumn"].Value = permisoIdSet.Contains(pantallaId);
    gvPermisos.EndEdit();
}
  • 第三步:调整权限加载时机,避免窗体未渲染完成时赋值被覆盖
    将CargarPrivilegios方法从构造函数移到窗体Load事件中执行:
// 构造函数修改为
public ManejarUsuario()
{
    InitializeComponent();
    IniciarComboBox();
    IniciarGV();
    if (UsuarioEditar.idUsuario != 0)
    {
        CargarDatos();
        btnCrearUsuario.Text = "Editar";
    }
}

// 新增窗体Load事件处理
private void ManejarUsuario_Load(object sender, EventArgs e)
{
    if (UsuarioEditar.idUsuario != 0)
    {
        CargarPrivilegios();
    }
}

内容的提问来源于stack exchange,提问作者Roberto González Moreno

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:18:01