How to Put CheckBoxes Dynamically in Data GridView of Window Application

Step 1: Write the Following code in the binding event of data GridView
 

DataGridViewCheckBoxColumn chbx_Column = new DataGridViewCheckBoxColumn();

chbx_Column.Name = "chk_column";

chbx_Column.HeaderText = "";

chbx_Column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

dataGridView1.Columns.Add(chbx_Column);

 

 //Select cell where checkbox to be display

Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(0, -1, true);            //0 Column index -1(header row) is row index

 

//Mention size of the checkbox

chkbox.Size = new Size(18, 18);

//set position of header checkbox where to places

rect.Offset(40, 2);

 chkbox.Location = rect.Location;

 

chkbox.CheckedChanged += chkBoxChange;

 

//Add CheckBox control to datagridView

this.dataGridView1.Controls.Add(chkbox);

 

// for adding combo box in header

Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(0, -1, true);            //0 Column index -1(header row) is row index

ComboBox c = new ComboBox();

c.BackColor = Color.FromArgb(246, 246, 246);

c.Size = new Size(100,15);

rect.Offset(0, 0);

c.Location = rect.Location;

this.dataGridView1.Controls.Add(c);

Step 2: For individual row ,write event code. This is just to uncheck the checked row and check the unchecked row

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
     if( Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["chk_column"].Value)== true)
          
     {
         dataGridView1.Rows[e.RowIndex].Cells["chk_column"].Value =false;
     } 
     else
     {
        dataGridView1.Rows[e.RowIndex].Cells["chk_column"].Value = true;
     }
}

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now