winform :DataGridView添加一列checkbox

时间:2022-11-17 19:39:31

   #region 添加checkbox列      

     public void AddCheckBox()
        {

                DataGridViewCheckBoxColumn columncb = new DataGridViewCheckBoxColumn();
                columncb.HeaderText = "选择";
                columncb.Name = "cb_check";
                columncb.TrueValue = true;
                columncb.FalseValue = false;
                columncb.DataPropertyName = "IsChecked";
                UserGridView.Columns.Insert(0,columncb);    //添加的checkbox在第一列
                //UserGridView.Columns.Add(columncb);     //添加的checkbox在最后一列

        }
        #endregion

 

在DataGridView控件的CellMouseClick属性中:点击数据勾选上checkbox

        private void UserGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {

            //checkbox 勾上
            if ((bool)UserGridView.Rows[e.RowIndex].Cells[0].EditedFormattedValue == true)
            {
                this.UserGridView.Rows[e.RowIndex].Cells[0].Value = false;
            }
            else
            {
                this.UserGridView.Rows[e.RowIndex].Cells[0].Value = true;
            }

        }