简体   繁体   English

C# winform 复选框仍然被选中

[英]C# winform checkbox still checked

In a button click function, I set checkbox.check = false;在按钮单击功能中,我设置了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"我将 MessageBox 设置为显示复选框值,但值为“False”

How can I set checkbox is unchecked when I click botton?当我单击 botton 时,如何设置复选框未选中?

Thanks a lot非常感谢

In the button click method you instantiate a new checkbox and the state of it is always set to false.在按钮单击方法中,您实例化一个新复选框,并且它的状态始终设置为 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当我再次单击按钮时,复选框未选中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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