24

Can someone help me why it doesn't work? I have a checkbox and if I click on it, this should uncheck all the checkbox inside the datagridview which were checked before including the user selected checkbox.

Here is the code:

        private void chkItems_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in datagridview1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
                if (chk.Selected == true)
                {
                    chk.Selected = false;
                }
                else
                {
                    chk.Selected = true;
                }
            }
        }

the checkbox should not be selected. it should be checked.

here is the added column

            DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
            CheckBox chk = new CheckBox();
            CheckboxColumn.Width = 20;
            datagridview1.Columns.Add(CheckboxColumn);
VMAtm
  • 27,943
  • 17
  • 79
  • 125
user1647667
  • 1,269
  • 4
  • 14
  • 26

17 Answers17

36

Looking at this MSDN Forum Posting it suggests comparing the Cell's value with Cell.TrueValue.

So going by its example your code should looks something like this:(this is completely untested)

Edit: it seems that the Default for Cell.TrueValue for an Unbound DataGridViewCheckBox is null you will need to set it in the Column definition.

private void chkItems_CheckedChanged(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
        if (chk.Value  == chk.TrueValue)
        {
            chk.Value = chk.FalseValue;
        }
        else
        {
            chk.Value = chk.TrueValue;
        }
    }
}

This code is working note setting the TrueValue and FalseValue in the Constructor plus also checking for null:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
        CheckboxColumn.TrueValue = true;
        CheckboxColumn.FalseValue = false;
        CheckboxColumn.Width = 100;
        dataGridView1.Columns.Add(CheckboxColumn);
        dataGridView1.Rows.Add(4);
    }

    private void chkItems_CheckedChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
            if (chk.Value == chk.FalseValue || chk.Value == null)
            {
                chk.Value = chk.TrueValue;
            }
            else
            {
                chk.Value = chk.FalseValue;
            }

        }
        dataGridView1.EndEdit();
    }
}
Mark Hall
  • 53,938
  • 9
  • 94
  • 111
  • i tried this one, but it doesn't check all the checkbox either. – user1647667 Nov 12 '12 at 06:24
  • @user1647667 meaning it is checking some of them ? – Mark Hall Nov 12 '12 at 06:26
  • when i click on the separated checkbox. it will check all the checkbox inside the datagridview. – user1647667 Nov 12 '12 at 06:28
  • @user1647667 I understand that is what you want, my question was wether or not my example checked anything? – Mark Hall Nov 12 '12 at 06:34
  • @user1647667 if you put a breakpoint on `chk.Value == chk.TrueValue` what is the value of TrueValue ? – Mark Hall Nov 12 '12 at 06:46
  • @user1647667 I think this will not work if the user selected second or a high index value checkbox. Did you check it? – Mr_Green Nov 12 '12 at 07:03
  • 2
    @Mr_Green In one of his comments he mentioned a seperated Checkbox, that is how I handled it. The main issue was that since the column was not databound there were no values set for TrueValue and FalseValue therefore we were checking for null. – Mark Hall Nov 12 '12 at 07:08
7

I was making my own version of a Checkbox to control a DataGridViewCheckBoxColumn when I saw this post wasn't actually answered. To set the checked state of a DataGridViewCheckBoxCell use:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    dataGridView1.Rows[row.Index].SetValues(true);
}

For anyone else trying to accomplish the same thing, here is what I came up with.

This makes the two controls behave like the checkbox column in Gmail. It keeps functionality for both mouse and keyboard.

using System;
using System.Windows.Forms;

namespace Check_UnCheck_All
{
    public partial class Check_UnCheck_All : Form
    {
        public Check_UnCheck_All()
        {
            InitializeComponent();
            dataGridView1.RowCount = 10;
            dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvApps_CellContentClick);
            this.dataGridView1.CellMouseUp += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.myDataGrid_OnCellMouseUp);
            this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.myDataGrid_OnCellValueChanged);
            this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click);
        }

        public int chkInt = 0;
        public bool chked = false;

        public void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
            {
                DataGridViewCheckBoxCell chk = dataGridView1.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell;

                if (Convert.ToBoolean(chk.Value) == true) chkInt++;
                if (Convert.ToBoolean(chk.Value) == false) chkInt--;
                if (chkInt < dataGridView1.Rows.Count && chkInt > 0)
                {
                    checkBox1.CheckState = CheckState.Indeterminate;
                    chked = true;
                }
                else if (chkInt == 0)
                {
                    checkBox1.CheckState = CheckState.Unchecked;
                    chked = false;
                }
                else if (chkInt == dataGridView1.Rows.Count)
                {
                    checkBox1.CheckState = CheckState.Checked;
                    chked = true;
                }
            }
        }
        public void myDataGrid_OnCellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            // End of edition on each click on column of checkbox
            if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
            {
                dataGridView1.EndEdit();
            }
            dataGridView1.BeginEdit(true);
        }
        public void dgvApps_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.CurrentCell.GetType() == typeof(DataGridViewCheckBoxCell))
            {
                if (dataGridView1.CurrentCell.IsInEditMode)
                {
                    if (dataGridView1.IsCurrentCellDirty)
                    {
                        dataGridView1.EndEdit();
                    }
                }
                dataGridView1.BeginEdit(true);
            }
        }
        public void checkBox1_Click(object sender, EventArgs e)
        {
            if (chked == true)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                    if (chk.Value == chk.TrueValue)
                    {
                        chk.Value = chk.FalseValue;
                    }
                    else
                    {
                        chk.Value = chk.TrueValue;
                    }
                }
                chked = false;
                chkInt = 0;
                return;
            }
            if (chked == false)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    dataGridView1.Rows[row.Index].SetValues(true);
                }
                chked = true;
                chkInt = dataGridView1.Rows.Count;
            }
        }
    }
}
Kevin Denham
  • 519
  • 1
  • 6
  • 24
4

Simple code for you it will work

private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dgv.CurrentRow.Cells["ColumnNumber"].Value != null && (bool)dgv.CurrentRow.Cells["ColumnNumber"].Value)
    {
        dgv.CurrentRow.Cells["ColumnNumber"].Value = false;
        dgv.CurrentRow.Cells["ColumnNumber"].Value = null;
    }
    else if (dgv.CurrentRow.Cells["ColumnNumber"].Value == null )
    {
        dgv.CurrentRow.Cells["ColumnNumber"].Value = true;
    }
}
Karl Gjertsen
  • 4,690
  • 8
  • 41
  • 64
3

The code you are trying here will flip the states (if true then became false vice versa) of the checkboxes irrespective of the user selected checkbox because here the foreach is selecting each checkbox and performing the operations.

To make it clear, store the index of the user selected checkbox before performing the foreach operation and after the foreach operation call the checkbox by mentioning the stored index and check it (In your case, make it True -- I think).

This is just logic and I am damn sure it is correct. I will try to implement some sample code if possible.

Modify your foreach something like this:

    //Store the index of the selected checkbox here as Integer (you can use e.RowIndex or e.ColumnIndex for it).
    private void chkItems_CheckedChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in datagridview1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
            if (chk.Selected == true)
            {
                chk.Selected = false;
            }
            else
            {
                chk.Selected = true;
            }
        }
    }
    //write the function for checking(making true) the user selected checkbox by calling the stored Index

The above function makes all the checkboxes true including the user selected CheckBox. I think this is what you want..

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • it works. but what if i want it not be be selected and i want it to be checked. – user1647667 Nov 12 '12 at 06:11
  • use `chk.Checked` instead of `chk.Selected` – Mr_Green Nov 12 '12 at 06:12
  • chk.Checked has error. "DataGridViewCheckBoxCell does not contain "checked" what will i do with this? – user1647667 Nov 12 '12 at 06:16
  • @Mr_Green that is not an option for a `DataGridViewCheckBox` unfortunatly – Mark Hall Nov 12 '12 at 06:17
  • @MarkHall yes I edited it by seeing your post. I think it should work now. – Mr_Green Nov 12 '12 at 06:19
  • it doesn't check any checkbox. it works when i used chk.select. but when i used chk.value.. its not checking any checkbox at all – user1647667 Nov 12 '12 at 06:21
  • Then use `Chk.Selected` only and instead of unchecking the selected Index, Check it. Its not clear what you want. Please state it again if I misunderstood it. – Mr_Green Nov 12 '12 at 06:24
  • @mr_green i tried the code that u edited. using chk.selected works. but what i need is the checkbox must check and not selected. and i used chk.checked but datagridview doesn't contain "checked". – user1647667 Nov 12 '12 at 06:31
  • Do you mean the user checked checkbox should be `true` and other checkboxes inside the same column should also be `true` if there previous value was `false`. right ? – Mr_Green Nov 12 '12 at 06:33
  • go with this [**link**](http://www.codeproject.com/Questions/155743/DataGridView-CheckBoxCell-Checked-Property) – Mr_Green Nov 12 '12 at 06:34
  • @user1647667 check my edited answer. I hope this should work. – Mr_Green Nov 12 '12 at 06:41
  • @mr_green it doesn't check anything again. =( – user1647667 Nov 12 '12 at 06:46
  • so the problem is that it is not checking the **user selected checkbox**. and for other checkboxes the code is working fine. thats it. right? – Mr_Green Nov 12 '12 at 06:48
  • yes that's right. even if i use the breakpoint. it doesn't show the checked checkbox and that's really my problem. – user1647667 Nov 12 '12 at 06:52
2

You can use this code on your grid CellClick event for check or unchecked cell checkbox :

private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 0)
        {
            Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = (Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null ? true : (!(bool)Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value));
        }
    }
1

Try the below code it should work

private void checkBox2_CheckedChanged(object sender, EventArgs e) 
{
    if (checkBox2.Checked == false)
    {
        foreach (DataGridViewRow row in dGV1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
            chk.Value = chk.TrueValue;
        }
    }
   else if (checkBox2.Checked == true)
    {
        foreach (DataGridViewRow row in dGV1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
            chk.Value = 1;
            if (row.IsNewRow)
            {
                chk.Value = 0;
            }
        }
    }
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

While all the other answers are correct, I'll add another simple option which worked for me:

var r = dataGridView.Rows[rIndex];
var c = r.Cells[cIndex];
var value = (bool) c.Value; 
c.Value = !value;

Compressed:

var r = dataGridView.Rows[rIndex];
r.Cells[cIndex].Value = !((bool) r.Cells[cIndex].Value)

As long as cIndex refers to a cell that is of type DataGridViewCheckBoxCell, this will work fine. Hope this helps somone.

0

you can try this code:

DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.CurrentRow.Cells[0];
                dataGridView1.BeginEdit(true);
                if (chk.Value == null || (int)chk.Value == 0)
                {
                    chk.Value = 1;
                }
                else
                {
                    chk.Value = 0;
                }
                dataGridView1.EndEdit();
Ba Dao
  • 1
  • 1
0

Below Code is working perfect

Select / Deselect a check box column on data grid by using checkbox CONTROL

    private void checkBox2_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox2.Checked == false)
        {
            foreach (DataGridViewRow row in dGV1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];

                    chk.Value = chk.TrueValue;
            }
       }
       else if(checkBox2.Checked==true)
       {
            foreach (DataGridViewRow row in dGV1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                chk.Value = 1;
                if (row.IsNewRow)
                {
                    chk.Value = 0;
                }
            }
        }
    }
poudigne
  • 1,694
  • 3
  • 17
  • 40
0
// here is a simple way to do so

//irate through the gridview
            foreach (DataGridViewRow row in PifGrid.Rows)
            {
//store the cell (which is checkbox cell) in an object
                DataGridViewCheckBoxCell oCell = row.Cells["Check"] as DataGridViewCheckBoxCell;

//check if the checkbox is checked or not
                bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);

//if its checked then uncheck it other wise check it
                if (!bChecked)
                {
                    row.Cells["Check"].Value = true;

                }
                else
                {
                    row.Cells["Check"].Value = false;

                }
            }
Vikas Bansal
  • 10,662
  • 14
  • 58
  • 100
0

I had the same problem, and even with the solutions provided here it did not work. The checkboxes would simply not change, their Value would remain null. It took me ages to realize my dumbness:

Turns out, I called the form1.PopulateDataGridView(my data) on the Form derived class Form1 before I called form1.Show(). When I changed up the order, that is to call Show() first, and then read the data and fill in the checkboxes, the value did not stay null.

zeeMonkeez
  • 5,057
  • 3
  • 33
  • 56
0

The code bellow allows the user to un-/check the checkboxes in the DataGridView, if the Cells are created in code

private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];

    if (chk.Value == chk.TrueValue)
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
    }
    else
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
    }

}
Tassisto
  • 9,877
  • 28
  • 100
  • 157
0

Here is another example you can try

private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == dataGridView.Columns["Select"].Index)
        {
            dataGridView.EndEdit();

            if ((bool)dataGridView.Rows[e.RowIndex].Cells["Select"].Value)
            {
                //-- checking current select, needs to uncheck any other cells that are checked
                foreach(DataGridViewRow row in dataGridView.Rows)
                {
                    if (row.Index == e.RowIndex)
                    {
                        dataGridView.Rows[row.Index].SetValues(true);
                    }
                    else
                    {
                        dataGridView.Rows[row.Index].SetValues(false);
                    }
                }
            }
        }
    }
ondrovic
  • 1,105
  • 2
  • 23
  • 40
0

All of the casting causes errors, nothing here I tried worked, so I fiddled around and got this to work.

  foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[0].Value != null && (bool)row.Cells[0].Value)
            {
                Console.WriteLine(row.Cells[0].Value);
            }

        }
0

I use the CellMouseUp event. I check for the proper column

if (e.ColumnIndex == datagridview.Columns["columncheckbox"].Index)

I set the actual cell to a DataGridViewCheckBoxCell

dgvChkBxCell = datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;

Then check to see if it's checked using EditingCellFormattedValue

if ((bool)dgvChkBxCell.EditingCellFormattedValue) { }

You will have to check for keyboard entry using the KeyUp event and check the .value property and also check that the CurrentCell's column index matches the checkbox column. The method does not provide e.RowIndex or e.ColumnIndex.

Hessam
  • 1,377
  • 1
  • 23
  • 45
Tom Wood
  • 1
  • 1
0

that worked for me after clearing selection, BeginEdit and change the girdview rows and end the Edit Mode.

 if (dgvDetails.RowCount > 0)
                    {
                        dgvDetails.ClearSelection(); 
                        dgvDetails.BeginEdit(true); 
                      
                        foreach (DataGridViewRow dgvr in dgvDetails.Rows)
                        {
                            dgvr.Cells["cellName"].Value = true;
                        }
                        dgvDetails.EndEdit();
                    }
Khushboo Tahir
  • 627
  • 9
  • 9
0

This is how I did it.

private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
{

    if(Convert.ToBoolean(this.Grid.Rows[e.RowIndex].Cells["Selected"].Value) == false)
    {
        this.Grid.Rows[e.RowIndex].Cells["Selected"].Value = true;
    }
    else
    {
        this.productSpecGrid.Rows[e.RowIndex].Cells["Selected"].Value = false;
    }
}
Eduards
  • 1,734
  • 2
  • 12
  • 37