首页 > 解决方案 > C#如何检查是否选中了任何datagridview复选框

问题描述

我想在选中任何 datagridviewcheckbox 时触发一个事件。我尝试了 foreach 但它仅在检查所有 datagridviewcheck 时触发。如果选中任何datagridviewcheckboxcell ,我想触发一个事件。

foreach (DataGridViewRow row in dgvLocal.Rows)
{
    if ((Convert.ToBoolean(row.Cells[0].Value) == true))
    {
        //
    }               
}

标签: c#

解决方案


使用 datagridview 的 cellcontentclicked 事件也使用 CurrentCellDirtystateChanged 来确保最后一次点击被提交

  void grd_CurrentCellDirtyStateChanged(object sender, EventArgs e)
            {
                if (grd.IsCurrentCellDirty)
                    grd.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }


    private void grd_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {


            if (e.ColumnIndex == 1) //compare to checkBox column index
            {
                DataGridViewCheckBoxCell cbx = (DataGridViewCheckBoxCell)grd[e.ColumnIndex, e.RowIndex];
                if (!DBNull.Value.Equals(cbx.Value) && (bool)cbx.Value == true)
                {
                    //checkBox is checked - do the code in here!
                }
                else
                {
                    //if checkBox is NOT checked (unchecked)
                }
            }
        }

推荐阅读