2

我想从datagridview(True / False)获取复选框值,但我总是得到一个值“null”,这是我获取复选框值的代码:

DataGridViewCheckBoxCell boolean = (DataGridViewCheckBoxCell)dgv[e.ColumnIndex, e.RowIndex];
string checkCheckboxChecked = ((bool)boolean.FormattedValue) ? "False" : "True";

即使选中了复选框,此代码也会返回一个false ,我也尝试了另一个:Boolean.FormattedValue

object value = dgvVisual[e.ColumnIndex, e.RowIndex].Value;

这段代码返回 null 值

为什么会这样?

PSe是一个事件CELL CONTENT CLICK

这是datagridview单元格内容点击的完整代码:

private void dgvVisual_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    int Number1= int.Parse(dgvVisual[0, e.RowIndex].Value.ToString());
    int Number2 = (e.ColumnIndex - 1);                
    DataGridViewCheckBoxCell boolean = (DataGridViewCheckBoxCell)dgvVisual[e.ColumnIndex, e.RowIndex];
    bool checkCheckboxChecked = (null != boolean && null != boolean.Value && true == (bool)boolean.Value);
    //string checkCheckboxChecked = "";
    if (checkCheckboxChecked)
    {
        //do something if the checkbox is checked
    }
    else
    {
        //do something if the checkbox isn't
    }
}

已解决:我更改CELL END EDIT EVENT并将点击内容添加datagridview.CurrentCell到另一个单元格。

4

1 回答 1

1

将单元格称为布尔值有点奇怪。然后使用它的FormattedValue属性。我DataGridView在表单中添加了 a,添加了两列TextCheckbox. CheckBox是一个DataGridViewCheckBoxColumn。然后我添加了一个按钮,这应该给你的想法:

private void button1_Click(object sender, EventArgs e)
{
    dgv.AutoGenerateColumns = false;
    DataTable dt = new DataTable();
    dt.Columns.Add("Text");
    dt.Columns.Add("CheckBox");
    for (int i = 0; i < 3; i++)
    {
        DataRow dr = dt.NewRow();
        dr[0] = i.ToString();
        dt.Rows.Add(dr);
    }
    dgv.DataSource = dt;            
}

private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    foreach (DataGridViewRow row in dgv.Rows)
    {
        var oCell = row.Cells[1] as DataGridViewCheckBoxCell;
        bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);
    }
}
于 2012-07-21T02:08:29.570 回答