0

在数据网格视图中,我需要在行上循环并获取包含选中复选框的行 dgv.rows[i].cells[0].value在这两种情况下都返回空所有这一切都发生在事件CellContentClick上

4

3 回答 3

0
static class DataGridViewExtensions
{
    public static IEnumerable<DataGridViewRow> CheckedRows(this DataGridView dgv, string checkedColumnName)
    {
        return CheckedRows(dgv, dgv.Columns[checkedColumnName].Index);
    }

    public static IEnumerable<DataGridViewRow> CheckedRows(this DataGridView dgv, int checkedColumnIndex)
    {
        foreach (DataGridViewRow row in dgv.Rows)
        {
            DataGridViewCheckBoxCell cell = row.Cells[checkedColumnIndex] as DataGridViewCheckBoxCell;
            Debug.Assert(cell != null, "The column specified is not a check box column");
            if (cell != null && (bool)cell.Value)
                yield return row;
        }
    }
}
于 2011-02-19T16:08:54.253 回答
0

尝试:

'VB
Dim MyCheckBox As CheckBox = _
    CType(dgv.rows[i].cells[0].findcontrol("checkbox_id"), CheckBox)

C#:

//C#
CheckBox MyCheckBox =
    dgv.Rows[i].Cells[0].FindControl("checkbox_id") as CheckBox;

当单元格不包含任何其他控件时,单元格上的 Value 属性引用文本内容。

于 2011-02-17T14:42:12.280 回答
0

如果复选框不包含任何数据,则结果将为空值。您可以使用bool.Parse()假设值不为空来解析循环中的值,即

for ( int i = 0; i < dgv.Rows.Count; i++ )
{
    var val = dgv.Rows[i].Cells[0].Value;
    if ( val == null ) { continue; }

    bool isChecked = bool.Parse( val.ToString() );
}
于 2011-02-17T16:58:29.510 回答