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

C#:如何获取DataGridView单元格值?解决复选框列代码报错

DataGridView复选框列判断错误的原因与修正

错误原因

第二段代码的问题很明确:datagrid.Rows[i].Cells[0]获取的是DataGridViewCell实例,它是一个对象,不是复选框的选中状态值。你直接把这个单元格对象和布尔值true做比较,属于类型不匹配,编译器自然会抛出“无法将‘bool’转换为‘System.Windows.Forms.DataGridViewCell’”的错误。

正确写法解析

第一段代码是可行的,因为它取了单元格的.Value属性——这才是存储复选框选中状态(bool类型)的地方,再通过.Equals(true)判断是否选中。

你也可以用更简洁的强制转换写法(注意确保单元格Value不为null,避免空引用异常):

for (int i = 0; i < datagrid.RowCount; i++)
{
    // 跳过DataGridView自动生成的新行
    if (datagrid.Rows[i].IsNewRow) continue;
    
    if ((bool)datagrid.Rows[i].Cells[0].Value)
    {
        string name = datagrid.Rows[i].Cells[1].Value.ToString();
        // 这里可以添加对name的后续处理逻辑
    }
}

额外优化:用foreach简化遍历

如果不想手动维护索引,也可以直接遍历DataGridView的Rows集合:

foreach (DataGridViewRow row in datagrid.Rows)
{
    if (row.IsNewRow) continue;
    
    if ((bool)row.Cells[0].Value)
    {
        string name = row.Cells[1].Value.ToString();
        // 处理逻辑
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:35:29