How to create check box column in datagridview C#.NET?


In this article I am going to explain about how to show checkbox column in the datagridview control in C#.NET windows application. Using this simple code to create check box column in your project.

Description


For example we are displayed large number of data in the datagridview control, sometimes we need to delete more number of records from the database or processed only some records in the datagridview. In that situation we are used checkbox column.

Based on the checkbox column selection perform delete or any other process. In this code snippet I am explained in detail about that process.

1) Create instance for checkbox class

CheckBox chkbox=new CheckBox();
Program p=new Program();
DataTable dt = new DataTable();

2) Load some static data in the datagridview control


private void Form1_Load(object sender, EventArgs e)
{

loadGrid();
}

void loadGrid()
{
dataGridView1.AllowUserToAddRows = false;

//Below i create on check box column in the datagrid view
dataGridView1.Columns.Clear();
DataGridViewCheckBoxColumn colCB = new DataGridViewCheckBoxColumn();

//set name for the check box column
colCB.Name = "chkcol";
colCB.HeaderText = "";
//If you use header check box then use it
colCB.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns.Add(colCB);


//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);


DataRow dr = default(DataRow);

//Declare Column names
dt.Columns.Add("eno");
dt.Columns.Add("empname");
dt.Columns.Add("sal");

//Create rows with data
dr = dt.NewRow();
dr["eno"] = 101;
dr["empname"] = "test1";
dr["sal"] = 9000;
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["eno"] = 102;
dr["empname"] = "test2";
dr["sal"] = 15000;
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["eno"] = 103;
dr["empname"] = "test3";
dr["sal"] = 20000;
dt.Rows.Add(dr);

//Bind that datatable data into the datagridview
dataGridView1.DataSource = dt;
}


3) Add Event Handler code if user select Header checkbox to select all check box in that datagrid view using below code

private void chkBoxChange(object sender, EventArgs e)
{
for (int k = 0; k <= dataGridView1.RowCount - 1; k++)
{
this.dataGridView1[0, k].Value = this.chkbox.Checked;
}
this.dataGridView1.EndEdit();
}


4) Display selected checkbox row records in text box

private void button1_Click(object sender, EventArgs e)
{
int i = 0;
List ChkedRow = new List();

for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true)
{
ChkedRow.Add(i);
}
}

if (ChkedRow.Count == 0)
{
MessageBox.Show("Select atleast one checkbox");
return;
}

foreach (int k in ChkedRow)
{
textBox1.Text = dataGridView1.Rows[k].Cells[1].Value.ToString();
textBox2.Text = dataGridView1.Rows[k].Cells[2].Value.ToString();
textBox3.Text = dataGridView1.Rows[k].Cells[3].Value.ToString();
}
}


5) If you want user select only one checkbox in that datagridview use this code to block multiple selection of checkbox


private void dataGridView1_CellClick(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
if (Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["chkcol"].Value) == false)
{
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
dataGridView1.Rows[i].Cells["chkcol"].Value = false;
}
}
}
}


6) If you want added sum of salary based on the selection use this code

private void dataGridView1_CellContentClick(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
double k = 0.0;
if (e.ColumnIndex == 0)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
{
//chkcol is checkbox column
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true)
{
k = k + Convert.ToDouble(dataGridView1.Rows[i].Cells[3].Value); //3 is salary column
}
}
//This one is total display textbox
textBox3.Text = k.ToString();
}
}


7) Delete selected records from the datagridview use below code

private void button2_Click(object sender, EventArgs e)
{
List ChkedRow = new List();
DataRow dr;

for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true)
{
ChkedRow.Add(i);
}
}

foreach (int k in ChkedRow)
{
dr = dt.Rows[k];
dt.Rows[k].Delete();
//dt.Rows.Remove(dr);
}
}


Full source Code


Design Side


Placed one datagridview control in the form design.

Code behind



using System.Text;
using System.Windows.Forms;

namespace CShChkColumn
{
public partial class Form1 : Form
{
CheckBox chkbox=new CheckBox();
Program p=new Program();
DataTable dt = new DataTable();

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

loadGrid();
}

void loadGrid()
{
dataGridView1.AllowUserToAddRows = false;

//Below i create on check box column in the datagrid view
dataGridView1.Columns.Clear();
DataGridViewCheckBoxColumn colCB = new DataGridViewCheckBoxColumn();

//set name for the check box column
colCB.Name = "chkcol";
colCB.HeaderText = "";
//If you use header check box then use it
colCB.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns.Add(colCB);


//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);


DataRow dr = default(DataRow);

//Declare Column names
dt.Columns.Add("eno");
dt.Columns.Add("empname");
dt.Columns.Add("sal");

//Create rows with data
dr = dt.NewRow();
dr["eno"] = 101;
dr["empname"] = "test1";
dr["sal"] = 9000;
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["eno"] = 102;
dr["empname"] = "test2";
dr["sal"] = 15000;
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["eno"] = 103;
dr["empname"] = "test3";
dr["sal"] = 20000;
dt.Rows.Add(dr);

//Bind that datatable data into the datagridview
dataGridView1.DataSource = dt;
}

private void chkBoxChange(object sender, EventArgs e)
{
for (int k = 0; k <= dataGridView1.RowCount - 1; k++)
{
this.dataGridView1[0, k].Value = this.chkbox.Checked;
}
this.dataGridView1.EndEdit();
}

private void button1_Click(object sender, EventArgs e)
{
int i = 0;
List ChkedRow = new List();

for (i = 0; i <= dataGridView1.RowCount - 1; i++) {
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true) {
ChkedRow.Add(i);
}
}

if (ChkedRow.Count == 0) {
MessageBox.Show("Select atleast one checkbox");
return;
}

foreach (int k in ChkedRow) {
textBox1.Text = dataGridView1.Rows[k].Cells[1].Value.ToString();
textBox2.Text = dataGridView1.Rows[k].Cells[2].Value.ToString();
textBox3.Text = dataGridView1.Rows[k].Cells[3].Value.ToString();
}
}

//Below method is used check only one checkbox in grid view uncomment if you want user select only one checkbox
private void dataGridView1_CellClick(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
//if (e.ColumnIndex == 0)
//{
// if (Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["chkcol"].Value) == false)
// {
// for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
// {
// dataGridView1.Rows[i].Cells["chkcol"].Value = false;
// }
// }
//}
}

//Un comment below code if you want add total if user select checkbox
private void dataGridView1_CellContentClick(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
//double k = 0.0;
//if (e.ColumnIndex == 0)
//{
// dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
// for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
// {
// //chkcol is checkbox column
// if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true)
// {
// k = k + Convert.ToDouble(dataGridView1.Rows[i].Cells[3].Value); //3 is salary column
// }
// }
// //This one is total display textbox
// textBox3.Text = k.ToString();
//}

}

//Delete selected check box record from grid view
private void button2_Click(object sender, EventArgs e)
{
List ChkedRow = new List();
DataRow dr;

for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true)
{
ChkedRow.Add(i);
}
}

foreach (int k in ChkedRow)
{
dr = dt.Rows[k];
dt.Rows[k].Delete();
//dt.Rows.Remove(dr);
}
}
}
}

Output
The output is shows like this
Output

Source Code Detail:
I have attached source here download it and try to use checkbox column in datagridview

Front End : Form design
Code Behind: C#

Conclusion:
I hope this article help you to know about datagridview checkbox column.


Attachments

  • Source_code (43689-251055-DGV_chkbox_column.rar)
  • Comments

    Guest Author: Nethra30 Aug 2012

    Very useful post.

    Guest Author: Raman31 Aug 2012

    Thanks a lot Sir g....

    Author: fugio25 Nov 2012 Member Level: Bronze   Points : 0

    can not be deleted once the checkbox all

    Guest Author: Kamini13 Feb 2013

    how to use list in datagridview in c# sharp windows application explain with eg

    Guest Author: Kamini13 Feb 2013

    I having an error showing:No row can be added to a datagridview control that does not have columns.columns must be added first

    Guest Author: Msbh27 Jun 2013

    Thanks man thanks a lot needed it.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: