-4

默认为无复选框

当我运行程序并单击是复选框时,程序溢出

private void checkEdit1_Click(object sender, EventArgs e)
        {
            checkEdit2.Checked = false;
            textEdit1.Enabled = true;
            answered = true;
            optional = textEdit1.Text;

            if (!checkEdit1.Checked)
            {
                checkEdit1.Checked = true;
                checkEdit2.Checked = false;
                textEdit1.Enabled = true;
                optional = textEdit1.Text;
            }

        }

        private void checkEdit2_Click(object sender, EventArgs e)
        {
            checkEdit1.Checked = false;
            textEdit1.Enabled = false;
            answered = false;

            if (!checkEdit2.Checked)
            {
                checkEdit2.Checked = true;
                checkEdit1.Checked = false;
                textEdit1.Enabled = false;
                answered = false;
            }

        }

你认为是什么错误?

4

2 回答 2

1

而不是Click事件,您应该CheckedChanged以这种方式使用事件:

checkEdit1.CheckedChenged += new EventHandler(checkEdit1_CheckedChanged);
checkEdit2.CheckedChenged += new EventHandler(checkEdit2_CheckedChanged);

private void checkEdit1_CheckedChanged(object sender, EventArgs e)
{
    if(checkEdit1.Checked == checkEdit2.Checked)
      checkEdit2.Checked = !checkEdit.Checked;
}

private void checkEdit2_CheckedChanged(object sender, EventArgs e)
{
    if(checkEdit1.Checked == checkEdit2.Checked)
      checkEdit2.Checked = !checkEdit.Checked;
}

但在这种情况下,最好的方法是使用一组单选按钮。

于 2012-11-29T18:11:36.487 回答
0

假设这些方法已连接到checkEdit1并且checkEdit2我建议您不要更改checkEdit1incheckEdit1_Click因为它已经更改 - 仅修改备用的状态。

然而,当你修改对方的状态时,除非你小心,否则你会被回调。最终计算机放弃了——溢出!

正如@Cyborgx37 的评论中提到的,单选按钮是这里更好的用户体验选择!

一种可能的解决方案,将单个方法绑定到 OnClick to BOTH 复选框:

private bool internallyUpdating = false;

private void CheckboxClick(object sender, EventArgs e)
{
    if ( !internallyUpdating )
    {
        // Prevent subsequent changes
        internallyUpdating = true;

        // Exchange 'checked' state
        if ( sender == checkEdit1 )
        {
            checkEdit2.Checked = !checkEdit2.Checked;
        } 
        else // if (sender == checkEdit2)
        {
            checkEdit1.Checked = !checkEdit1.Checked;
        }

        // other logic here..

        // restore 'on change' functionality.
        internallyUpdating = false;
    }
于 2012-11-29T18:04:27.940 回答