开发者

C# Checkbox has strange behavior

开发者 https://www.devze.com 2022-12-11 05:37 出处:网络
When a winform first displays, the checkbox is unchecked by default.If when the form first displays, I click on the checkbox to \'check\' it, 开发者_如何学Gothe checkbox appears checked for a split se

When a winform first displays, the checkbox is unchecked by default. If when the form first displays, I click on the checkbox to 'check' it, 开发者_如何学Gothe checkbox appears checked for a split second and then disappears. The checkedchanged event never fires. However, if anytime after the first initial attempt I click on the checkbox, the value changes (checked to unchecked and vice versa) like it should and the event fires.

Any idea why the checkbox would not check on the first attempt? It appears selected the first time when you hover over it so I know it has focus.

Update: it doesn't matter if you enter data into all other controls first and then click on the checkbox, the first time you click on it, it flashes as checked for a second, and then the check disappears. Anytime after the 1st time though it works. Strange...


Hard to tell without seeing a code snippet. When I've had things like this in the past, it's been due to having duplicate control ids, or wiring up event handlers incorrectly. Have you tried disabling portions of your code and seeing what affects the checkbox behaviour?


Strangely, putting code in the CheckedChanged() to set the value (what it gets set to anyway if I trace through it) seems to work:

        if (this.chkbox1.Checked == true)
        {
            this.chkbox1.Value = "1";
            this.chkbox1.Text = "Checked";
        }
        else
        {
            this.chkbox1.Value = "0";
            this.chkbox1.Text = "Un-checked";
        }

I also put a focus() in the click():

        if (((System.Windows.Forms.MouseEventArgs)(e)).Clicks <= 1)
        {
            if (this.chkbox1.Focused == false)
            {
                this.chkbox1.Focus();
            }
        }

I have no idea why that fixes the problem, but it does.


do this happen with just one CB? or all the CB on the form.

Have you tried deleting the CB then adding it back?

I would suggest you post the code behind the CB?


For your custom code, I would try using different cast styles, to see if it makes any difference.

If you're using the standard C# syntax, and it fails (vanishing checkbox)

CheckBox checkBox = sender as CheckBox;

I would try using the old-style cast on the sender object and see if it gives you the desired result:

CheckBox checkBox = (CheckBox)sender;

This may give you a hint on the root cause.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号