none
Add a checkall checkbox in gridview C#

    Question

  • Hi all,

    I ve a gridview, for which i need checkall checkbox , once that is clicked all the checkboxes need to be selected or if any one of the checkboxes is unselected the check all check box shd be unselected.

    I need two things

    1. How to add this checkall check box to the grid view

    2. When this checkall checkbox is selected all the chk boxes under it needs to be selected


    Meghana Lohit
    Friday, July 02, 2010 5:18 AM

Answers

  • 1. adding checkbox column to dgw:

    private void AddingCheckBoxColumn()
    {
     DataGridViewCheckBoxColumn column3 = new DataGridViewCheckBoxColumn();
     column3.Name = "Column3";
     column3.HeaderText ="Check boxes";
     dataGridView1.Columns.Add(column3);
     dataGridView1.AutoSize = true;
     dataGridView1.AllowUserToAddRows = false;
     dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
     dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft; 
    
     for (int i = 0; i < dataGridView1.RowCount; i++)
     {
     dataGridView1.Rows[i].Cells["Column3"].Value = false;
     }
     button2.Visible = true;
    }

     

    2. checking all the checkboxes in the dgw`s column:

     private void button6_Click(object sender, EventArgs e)
     {
     //1st option:
     foreach (DataGridViewRow row in dataGridView1.Rows)
     {
     if (Convert.ToBoolean(row.Cells["Column3"].Value) == false)
     row.Cells["Column3"].Value = true;
     else
     row.Cells["Column3"].Value = false;
     }
    
     //2nd option:
     /*for (int i = 0; i < dataGridView1.RowCount; i++)
     {
     if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Column3"].Value) == false)
     dataGridView1.Rows[i].Cells["Column3"].Value = true;
     else
     dataGridView1.Rows[i].Cells["Column3"].Value = false;
     }*/ 
     }

     

     

    Friday, July 02, 2010 1:11 PM

All replies

  • is it completely necessary to have this 'Check All' checkbox in column header ? You can have a normal checkbox just above the gridview [top-left of gridview] and handle it's check state change to do it.

    Thanks

    Quizwith.NET is now open for everyone !

    Living on Earth may be expensive, but did you know that it includes a free trip around the sun? Isn't that worth it?
    Friday, July 02, 2010 5:29 AM
  • Sorry, I need c# code(for windows form not web application. Not asp.net. Can someone help me??
    Meghana Lohit
    Friday, July 02, 2010 10:27 AM
  • Actually you have post the requirement for gridview and gridview component is used in web application, in context of windows application it is datagridview..

    for datagridview you can find your solution here-

    http://tech.chitgoks.com/2008/11/17/c-add-select-all-deselect-all-checkbox-in-column-header-in-datagridview-control/

     

    regards

    jayant

    Friday, July 02, 2010 12:03 PM
  • 1. adding checkbox column to dgw:

    private void AddingCheckBoxColumn()
    {
     DataGridViewCheckBoxColumn column3 = new DataGridViewCheckBoxColumn();
     column3.Name = "Column3";
     column3.HeaderText ="Check boxes";
     dataGridView1.Columns.Add(column3);
     dataGridView1.AutoSize = true;
     dataGridView1.AllowUserToAddRows = false;
     dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
     dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft; 
    
     for (int i = 0; i < dataGridView1.RowCount; i++)
     {
     dataGridView1.Rows[i].Cells["Column3"].Value = false;
     }
     button2.Visible = true;
    }

     

    2. checking all the checkboxes in the dgw`s column:

     private void button6_Click(object sender, EventArgs e)
     {
     //1st option:
     foreach (DataGridViewRow row in dataGridView1.Rows)
     {
     if (Convert.ToBoolean(row.Cells["Column3"].Value) == false)
     row.Cells["Column3"].Value = true;
     else
     row.Cells["Column3"].Value = false;
     }
    
     //2nd option:
     /*for (int i = 0; i < dataGridView1.RowCount; i++)
     {
     if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Column3"].Value) == false)
     dataGridView1.Rows[i].Cells["Column3"].Value = true;
     else
     dataGridView1.Rows[i].Cells["Column3"].Value = false;
     }*/ 
     }

     

     

    Friday, July 02, 2010 1:11 PM
  • Hi if i open the page u ve suggested it shows a blank page, i m not able to find the solution, could u please suggest me the right link.

    http://tech.chitgoks.com/2008/11/17/c-add-select-all-deselect-all-checkbox-in-column-header-in-datagridview-control/


    Meghana Lohit

    Tuesday, September 14, 2010 9:07 AM
  • Hi, the code above I posted, works, only youi have to modify it a bit, regarding your needs. And please, the thread you created a couple of monhts ago and it was answered, you go and make it unanswered. Why didnt you start another thread.

    If you want me to help, please give me smore more information, a code would be good to start with.

    Wednesday, September 15, 2010 12:21 AM
  • Hi i marked it as answer, anyways my requirement is i need a checkbox at the top in column header, which i ve achieved but the problem is once i click on check all check box , all the subcheckboxes below it will be checked. The problem arises only when i uncheck one the sub check boxes. If any of the subcheckbox is unchecked then the main check box needs to unchecked which is not happening. only when i hover the mouse over the main check all check box it gets unselected.

    To make it clear

    1. I ve one check all check box.

    2. I ve 5 sub check boxes

    3. If I click on the check all check box , all these 5 sub check boxes get checked( which is working perfectly fine)

    4. Now if i uncheck any one of the 5 sub check box , then the main check all check box doesn get unchecked

    5. It gets unchecke donly when i hover the mouse over the check all check box.

    I hope u ve understood wat i m trying to say. I hope you can give me a solution to this

    I cld ve started a new thread, bt it will b marked as duplicate as the requirement is the same.

    I ve also pasted the code

     public partial class Form1 : Form
      {
        DGVColumnHeader dgvColumnHeader;
        bool chkallFalse = false;
    
        public Form1()
        {
          InitializeComponent();
    
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
    
          dgvColumnHeader = new DGVColumnHeader();
    
          dataGridView1.Columns[0].HeaderCell = dgvColumnHeader;
    
          ////Data Binding 
          DataTable dt = new DataTable();
          dt.Columns.Add("1");
    
          dt.Rows.Add("100");
          dt.Rows.Add("102");
          dt.Rows.Add("102");
          dt.Rows.Add("102");
          dataGridView1.DataSource = dt;
          foreach (DataGridViewRow row in dataGridView1.Rows)
          {
            row.Selected = false;
           }
    
          }
    
        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
          if (e.ColumnIndex == 0)
          {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
              dataGridView1.EndEdit();
              dataGridView1.Rows[i].Cells[0].Value = dgvColumnHeader.CheckAll;
            }
          }
        }
    
    ///This is DGV class which has the code
    
    
    class DGVColumnHeader : DataGridViewColumnHeaderCell
      {
        private Rectangle CheckBoxRegion;
        public bool checkAll = false;
    
        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates dataGridViewElementState,
          object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle,
          DataGridViewPaintParts paintParts)
        {
    
          base.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value,
            formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
    
          graphics.FillRectangle(new SolidBrush(cellStyle.BackColor), cellBounds);
    
          CheckBoxRegion = new Rectangle(cellBounds.Location.X + 1, cellBounds.Location.Y + 2, 25, cellBounds.Size.Height - 4);
    
    
          if (this.checkAll)
            ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Checked);
          else
            ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Normal);
    
          Rectangle normalRegion =
            new Rectangle(
            cellBounds.Location.X + 1 + 25,
            cellBounds.Location.Y,
            cellBounds.Size.Width - 26,
            cellBounds.Size.Height);
    
          graphics.DrawString(value.ToString(), cellStyle.Font, new SolidBrush(cellStyle.ForeColor), normalRegion);
        }
    
        protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
        {
          //Convert the CheckBoxRegion 
          Rectangle rec = new Rectangle(new Point(0, 0), this.CheckBoxRegion.Size);
          this.checkAll = !this.checkAll;
          if (rec.Contains(e.Location))
          {
            this.DataGridView.Invalidate();
          }
          
          base.OnMouseClick(e);
          
        }
        
        public bool CheckAll
        {
          get { return this.checkAll; }
          set { this.checkAll = value; }
        }
    
      }

    Meghana Lohit
    Wednesday, September 15, 2010 11:01 AM
  • THANK U, THIS IS VERY USEFUL TO ME
    Friday, September 17, 2010 10:48 AM
  • <asp:GridView ID="gvData" runat="server" AllowPaging="True" AutoGenerateColumns="False" >
    <Columns>
    <asp:TemplateField ItemStyle-Width="30px">
    <HeaderTemplate>
    <input type="checkbox" id="srCheck" name="srCheck" value="CheckAll" title="CheckAll" onclick="fnCheckAll(this);" />
    </HeaderTemplate>
    <ItemTemplate>
    <asp:CheckBox ID="chkAct" runat="server" CssClass="SRCheck" onclick="fnUnCheck(this);" />
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
    < /asp:GridView>

    <script type="text/javascript">
    function fnCheckAll() {
    var sts = $("#srCheck").attr("checked");
    //alert(sts);
    $(".SRCheck").each(function () {
    $(this).find("input").attr('checked', sts);
    });
    }
    function fnUnCheck(obj) {
    var sts = $("#" + obj.id).attr("checked");
    //alert(sts);
    if (sts == false)
    $("#srCheck").attr('checked', false);
    else {
    fnCheckUnCheckTop();
    }
    }

    function fnCheckUnCheckTop() {
    var allSts = true;
    $(".SRCheck").each(function () {
    var sts = $(this).find("input").attr("checked");
    if (sts == false)
    allSts = false;
    });
    if (allSts == true)
    $("#srCheck").attr('checked', true);
    else
    $("#srCheck").attr('checked', false);
    }
    </script>


    SChahal

    Thursday, June 14, 2012 12:10 PM
  • Thanks a lot for this.
    Thursday, June 14, 2012 12:11 PM
  • :)

    you are welcome, even if its an old one.


    Mitja

    Thursday, June 14, 2012 4:09 PM