Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
I am creating a project which developed projects for organizations as per there needs.
I assigned some of the employees for some project. And when the projects gets complete the employees are free.
For assigning i make use of datagridview check box column.
when i clicks on save button in the form, the checked row inserted into database...
Posted
Comments
[no name] 12-Mar-13 3:49am    
What have you tried please show the code.
Gaurav Jadhav 12-Mar-13 3:55am    
i never tried yet.. b'cz i dnt have any idea hw to do it...
[no name] 12-Mar-13 3:58am    
First you should try something from yourself.
if any issue get me at anuragsarkar19@gmail.com

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

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


2) Load some static data in the datagridview control
C#
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
C#
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
C#
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
C#
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
C#
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
C#
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


C#
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


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.




reference url - http://www.dotnetspider.com/resources/43689-How-create-check-box-column-datagridview.aspx[^]
 
Share this answer
 
v2
C#
for(int i=0;i<gridview1.rows.count;i++)
   {
    if((bool)gridview1.Rows[i].Cells["Table column Name"].Value==true)
   {
      //write the insert command i.e 
      str="insert into DemoTable("EmpName")   
            values("+convert.ToString(gridview1.Rows[i].Cells["Table_column_Name"].Value)+") ";
      con.Open();

      SqlCommand cmd = new SqlCommand(str, con);
      cmd.ExecuteNonQuery();
                
      con.Close();
   }
}

//let me know if it helps you or not.If it helps then don't forgot to like the answer
 
Share this answer
 
v2
Comments
CHill60 6-Apr-14 14:15pm    
Apart from your "solution" being incomplete this post is over a year old!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900