当前位置: 动力学知识库 > 问答 > 编程问答 >

winforms - C# Checkbox has strange behavior

问题描述:

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, the 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: