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

ASP.NET GridView获取byte字段值赋值Checkbox遇CS1061错误原因

问题

开发ASP.NET+C#应用时,用GridView展示记录,选中行后需将值同步到上方的文本框和复选框。处理RecordActive(byte类型)字段时,尝试用以下代码获取值:

String val = dgvHolidays.Rows[dgvHolidays.SelectedRow.RowIndex].Cells[3].Value.ToString();

运行时触发CS1061错误:

'TableCell' does not contain a definition for 'Value' and no accessible extension Method 'Value' accepting a first argumentof type 'TableCell' could be found (are you missing a using directive or an assembly reference?)

错误原因

ASP.NET Web Forms的GridView控件中,TableCell对象没有Value属性——你混淆了WinForms的DataGridViewCell(自带Value属性)和Web Forms的TableCell(仅通过Text属性存储渲染到页面的文本内容)。

Web Forms的GridView绑定数据后,单元格的原始数据不会保留在TableCell中,只能通过Text获取页面显示的文本,或者从绑定的数据源中直接提取原始值。

修正方案

方法1:直接使用TableCell的Text属性

利用单元格渲染后的文本值转换判断,适合字段值直接以"1"/"0"或"True"/"False"显示的场景:

private void DisplayValues()
{
    if (dgvHolidays.Rows.Count > 0)
    {
        // 处理Holiday_Date字段逻辑...

        // 处理RecordActive字段
        GridViewRow selectedRow = dgvHolidays.SelectedRow;
        if (selectedRow != null)
        {
            string activeText = selectedRow.Cells[3].Text.Trim();
            // 匹配byte类型的1/0或文本True/False
            chkbxRecordActive.Checked = activeText == "1" || activeText.Equals("True", StringComparison.OrdinalIgnoreCase);
        }
    }
}

方法2:从绑定数据源获取原始值(更可靠)

如果单元格文本被格式化(比如显示为"激活"/"未激活"),直接从绑定的DataRowView提取原始byte值:

private void DisplayValues()
{
    if (dgvHolidays.Rows.Count > 0)
    {
        // 处理Holiday_Date字段逻辑...

        // 处理RecordActive字段
        GridViewRow selectedRow = dgvHolidays.SelectedRow;
        if (selectedRow != null)
        {
            DataRowView rowData = selectedRow.DataItem as DataRowView;
            if (rowData != null)
            {
                byte activeStatus = Convert.ToByte(rowData["RecordActive"]);
                chkbxRecordActive.Checked = activeStatus == 1;
            }
        }
    }
}

注意:此方法需要保证调用DisplayValues时,GridView的DataItem仍处于可用状态(比如在SelectedIndexChanged事件中);若在PostBack后调用,需确保数据源已重新绑定或选中行数据已存入ViewState。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 01:48:38