0

我正在检查 GridView1_RowDataBound 事件中的复选框值,但出现错误“运算符不能应用于字符串或布尔类型的操作数”..

这是我的相同代码...

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 1; i < e.Row.Cells.Count - 2; i++)
        {
            CheckBox cb = new CheckBox();

            if (e.Row.Cells[i].ToString() == true)
            {
                cb.Checked = true;
            }
            else
            {
                cb.Checked = false;
            }
            e.Row.Cells[i].Controls.Add(cb);
        }
    }
}

请帮助我..提前谢谢..

4

1 回答 1

1

问题在这里:

if (e.Row.Cells[i].ToString() == true)
{
    cb.Checked = true;
}

您正在将字符串值Cells[i].ToString()与布尔值进行比较true

如果单元格包含表示真或假的字符串值,则需要将其解析为布尔值:

bool result;
if (Boolean.TryParse(e.Row.Cells[i].Value.ToString(), out result))
{
    if (result)
    {
        ....
    }
}
else
{
    // Item is not a valid boolean - throw an exception or just default to false
}
于 2013-09-21T09:20:54.997 回答