简体   繁体   中英

C# winform checkbox still checked

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

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM