1

In a button click function, I set checkbox.check = false; but when I click button again, checkbox still in checked

here is my code:

// Header全選加上CheckBox
System.Drawing.Rectangle rect = dataGridView1.GetCellDisplayRectangle(0, -1, true);
rect.X = rect.Location.X + rect.Width / 4 - 9;
rect.Y = rect.Location.Y + (rect.Height / 2 - 9);
SolidBrush solidBrush = new SolidBrush(Color.White);
System.Windows.Forms.CheckBox checkBox = new System.Windows.Forms.CheckBox();
checkBox.Name = "checkBoxHeader";
checkBox.Size = new Size(18, 18);
checkBox.Location = rect.Location;
//checkBox.AutoCheck = false;
//MessageBox.Show(checkBox.Checked.ToString());
checkBox.Checked = false;
checkBox.Invalidate();
checkBox.Update();
dataGridView1.RefreshEdit();
checkBox.CheckedChanged += new EventHandler(checkBox_CheckedChanged);
dataGridView1.Controls.Add(checkBox);

I set MessageBox to show checkbox value, but the value is "False"

How can I set checkbox is unchecked when I click botton?

Thanks a lot

iSuper
  • 11
  • 2
  • Make sure you do not have `InitializeComponent` running twice. That would problem in control behavior. Or Make sure you are not setting the `Checked` property somewhere else – styx Nov 02 '20 at 07:39
  • [DataGridView CheckBox selection bug](https://stackoverflow.com/a/63693094/7444103) – Jimi Nov 02 '20 at 12:48

2 Answers2

0

In the button click method you instantiate a new checkbox and the state of it is always set to false. You have to instantiate the checkbox and setting the properties of it in the constructor of your form or you can drag a checkbox onto the form when using the designer.

Example

private Checkbox _checkbox;

public Form1() 
{
    InitializeComponents();
    _checkbox = new CheckBox();
    //set properties
    _checkbox.Checked = true;
    //other properties you want to set
    //add checkbox to your form for example
    datagridview1.Controls.Add(_checkbox);
}

Then in your button click method just write:

_checkbox.Checked = false;
eisem
  • 185
  • 1
  • 10
0

Thanks for answering, I solve this question.

I set code as

foreach (Control ckb in dataGridView1.Controls)
{
    if (ckb is System.Windows.Forms.CheckBox)
    {
        ((System.Windows.Forms.CheckBox)ckb).Checked = false;
    }
}

and the checkbox is unchecked when I click button again

iSuper
  • 11
  • 2