Hi

Am using Visual studio 2008, C# application .
In my data grid view i have Checkbox column, I put One header check box for datagrid view.
datagridviewCheck box is displayed for all row. i wil create column header check box separately.
if am selecting the Header check box means all coumns below in the Check box column should get selected,
if am unchecked header check box all are unchecked. if am selecting one by one column check box in gridview while select last check box column header check box should be selected.
All check box are selected now un select the any one of thecheck box, header check box should be un checked,

i dont know how to do like this. pls any one help me. very urgent for me. advance thanks. I need code for above operations.

Recommended Answers

All 10 Replies

Try it,

DataTable dt = new DataTable();
        private void Form1_Load(object sender, EventArgs e)
        {
            dt.Columns.Add("No", typeof(int));
            dt.Columns.Add("CheckBox",typeof(bool));
            for (int i = 1; i < 10; i++)
                dt.Rows.Add(i, false);
            dataGridView1.DataSource = dt;
           
        }
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow r in dt.Rows)
                r[1] = checkBox1.Checked;

        }

Hi my problem is not solved

What is your problem? Please show us your code. We will not reply if you post source code without BB code tags. Read announcement.

What is your problem? Please show us your code. We will not reply if you post source code without BB code tags. Read announcement.

Hi

In my form window i will import csv file click show contact button contact details are displayed in the grid view. in gridview i put one header check box. if i click that header check box first row should not be selected remaining rows check box are selected.

My code here

private void dataGridContacts_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 0)
                {
                    int alltrue = 0;

                    for (int i = 0; i < dataGridContacts.Rows.Count; i++)
                    {
                        if (dataGridContacts.Rows[i].Cells[0].Value == null)
                        {
                            break;
                        }
                        if (Convert.ToBoolean(dataGridContacts.Rows[i].Cells[0].Value) == false)
                        {
                            dgvColumnHeader.CheckAll = false;
                            break;
                        }
                        else if (Convert.ToBoolean(dataGridContacts.Rows[i].Cells[0].Value) == true)
                        {
                            alltrue++;
                        }
                    }
                    if (alltrue == dataGridContacts.Rows.Count)
                    {
                        dgvColumnHeader.CheckAll = true;
                    }
                    clearCheckBox = false
               }
void ckBoxView_CheckedChanged(object sender, EventArgs e)
        {
            
            lblError.Text = string.Empty;
            if (clearCheckBox != false)
            {
                if (((CheckBox)sender).Checked == true)
                {
                    for (int i = 0; i < dataGridContacts.Rows.Count; i++)
                    {
                        
                        dataGridContacts.Rows[i].Cells[0].Value = true;
                        dataGridContacts.Rows[i].Cells[0].Selected = false;
                         
                        
                    }
                }
               
                if (((CheckBox)sender).Checked == false)
                {
                    for (int i = 0; i < dataGridContacts.Rows.Count; i++)
                    {
                         dataGridContacts.Rows[i].Cells[0].Value = false;
                        dataGridContacts.Rows[i].Cells[0].Selected = false;

                    }
                }
           }
            clearCheckBox = true;
        }

pls view my attachment

Hi,

I am using a datagrid view control in that i will import contact details and that contact details such name, address, email and category are displayed in grid view and also have one check box column, i put one checkbox header control.
if i click header check box all child check box should get selected,
if am click child check box one by one at last my header check box should get selected,
if am unselect header check box all child check boxes are unselected.
Header check box is selected, i will un select some child check boxes , header check box should get unselected instead of this all my child check box is cleared, i dont know how this occured. please anyone can help me. very urgent for me.

am using below code only

private void dataGridContacts_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 0)
                {
                    int alltrue = 1;
                   
                    for (int i = 0; i <= dataGridContacts.Rows.Count; i++)
                    {
                        
                            if (Convert.ToBoolean(dataGridContacts.Rows[i].Cells[0].Value) == true)
                            {
                                alltrue++;
                            }
                            else if (Convert.ToBoolean(dataGridContacts.Rows[i].Cells[0].Value) == false)
                            {
                                ((CheckBox)dataGridContacts.Controls["checkBoxColumn"]).Checked = false;
                                break;
                            }
                        }
   if (alltrue == dataGridContacts.Rows.Count)
                    {
                        ((CheckBox)dataGridContacts.Controls["checkBoxColumn"]).Checked = true;
                    }

                    else
                    {
                        
                       ((CheckBox)dataGridContacts.Controls["checkBoxColumn"]).Checked = false;
                    }
                    //clearCheckBox = false;
                }
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.Name = "IsCheck".Clone().ToString();
            checkBoxColumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            checkBoxColumn.HeaderText = "".Clone().ToString();
            dataGridContacts.Columns.Insert(0, checkBoxColumn);
            dataGridContacts.Columns["IsCheck"].ReadOnly = false;
            dataGridContacts.Columns["IsCheck"].Width = 55;
            dataGridContacts.Columns["IsCheck"].Visible = false;
                    
            CheckBox ckBoxView = new CheckBox();
            ckBoxView.Name = "checkBoxColumn";
             ckBoxView.Size = new Size(15, 15);
             ckBoxView.Location = new Point(23, 5);
            ckBoxView.CheckedChanged += new EventHandler(ckBoxView_CheckedChanged);
            //Add the CheckBox into the DataGridView
            this.dataGridContacts.Controls.Add(ckBoxView);
            dataGridContacts.Controls["checkBoxColumn"].Visible = false;
private void ckBoxView_CheckedChanged(object sender, EventArgs e)
        {
             lblError.Text = string.Empty;
             if (clearCheckBox != false)
             {
                 if (((CheckBox)sender).Checked == true)
                 {
                     for (int i = 0; i < dataGridContacts.Rows.Count; i++)
                     {
                         dataGridContacts.Rows[i].Cells[0].Selected = true;
                         dataGridContacts.Rows[i].Cells[0].Value = true;
                     }
                 }
                 if (((CheckBox)sender).Checked == false)
                 {
                     for (int i = 0; i < dataGridContacts.Rows.Count; i++)
                     {
                         dataGridContacts.Rows[i].Cells[0].Selected = false;
                         dataGridContacts.Rows[i].Cells[0].Value = false;
                     }
                 }
             }
            clearCheckBox = true;
        }

please any one can help me. what mistake i did.

commented: duplicate posts -3

Upload your project (delete .exe) zip please.

hi

shall i upload that code file only .(.cs file)

Drop a datagridview on a form and try this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace daniweb.dgv
{
  public partial class frmDataGridView5 : Form
  {
    private DataTable dt;
    private DGVColumnHeader colHead;
    private bool suspendEvents;

    public frmDataGridView5()
    {
      InitializeComponent();
    }

    /// <summary>
    /// Gets simulatation data
    /// </summary>
    /// <returns></returns>
    private static DataTable GetTestData()
    {
      DataTable result = new DataTable();
      result.Columns.Add(new DataColumn("RecordId", typeof(int)));
      result.Columns.Add(new DataColumn("Name", typeof(string)));
      for (int i1 = 1000; i1 <= 1008; i1++)
      {
        DataRow row = result.NewRow();
        row["RecordId"] = i1;
        row["Name"] = Guid.NewGuid().ToString();
        result.Rows.Add(row);
      }
      return result;
    }

    private void frmGridView5_Load(object sender, EventArgs e)
    {
      //DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
      //col1.Name = "colName";
      //col1.DataPropertyName = "RecordId";

      dt = GetTestData();
      dataGridView1.DataSource = dt;

      //initialize DGVColumnHeader object
      colHead = new DGVColumnHeader();

      //Add columns dynamically  to gridview
      dataGridView1.Columns.Insert(0, new DataGridViewCheckBoxColumn());
      dataGridView1.Columns[0].HeaderCell = colHead;

    }

    private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
      if (suspendEvents)
        return;

      if (e.ColumnIndex == 0)
      {
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
          if (!dataGridView1.Rows[i].IsNewRow)
            dataGridView1.Rows[i].Cells[0].Value = colHead.Checked;
        }
      }
    }

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (suspendEvents)
        return;

      if (e.ColumnIndex == 0)
      {
        bool allChecked = true;


        for (int i = 0; i < this.dataGridView1.RowCount; i++)
        {
          if (this.dataGridView1.Rows[i].IsNewRow)
            continue;

          bool colChecked = string.Compare(this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue.ToString(), "true", true) == 0;
          if (i == e.RowIndex)
            colChecked = !colChecked;

          if (!colChecked)
          {
            allChecked = false;
            break;
          }
        }

        if (allChecked)
        {
          suspendEvents = true;
          try
          {
            colHead.Checked = true;
            dataGridView1.InvalidateColumn(0);
          }
          finally
          {
            suspendEvents = false;
          }
        }
      }
    }
  }

  public class DGVColumnHeader : DataGridViewColumnHeaderCell
  {
    private Rectangle CheckBoxRegion;
    private bool _checked = 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._checked)
        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._checked = !this._checked;
      if (rec.Contains(e.Location))
      {
        this.DataGridView.Invalidate();
      }
      base.OnMouseClick(e);
    }

    public bool Checked
    {
      get { return this._checked; }
      set { this._checked = value; }
    }
  }

}

I have attached a sample project.

hi thank u for ur response.

am trying that way, i will click header check box child check boxes are selected after that i will unselect 1 child check box, again i will click header check box that time all my child check boxes are selected except one. that one is before unselected one. pls tell solve this sequence and while header check box is selected i will unselect the any of child check box , header check box should get unselected. very urgent for me. pls tell me.

Ah, I see the problem. Try this one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.