单击后禁用按钮

时间:2012-10-31 02:13:35

标签: c# winforms

我有3个按钮。

当我点击按钮1时,它将禁用按钮1,然后启用第二个按钮,然后进入与最后一个按钮相同的过程。但我认为我的代码有问题。当我点击第一个按钮时,它不会禁用

按钮1已启用,按钮2和3在加载时被禁用。

private void groupBox1_Enter(object sender, EventArgs e)
{
    Button btn = sender as Button;

    if (btn == button1)
    {
        button1.Enabled = false;
        button2.Enabled = true;
        button3.Visible = false;
        button3.Enabled = false;
        MessageBox.Show("button 1 disabled");
    }
    else if (btn == button2)
    {
        button1.Enabled = false;
        button2.Enabled = false;
        button3.Visible = true;
        button3.Visible = true;
        MessageBox.Show("button 2 disabled");
    }
    else if (btn == button3)
    {
        button1.Enabled = false;
        button2.Enabled = false;
        button3.Visible = false;
        button3.Visible = false;
        MessageBox.Show("button 3 disabled");
    }
}

4 个答案:

答案 0 :(得分:3)

您订阅了正确的活动吗?它表示groupBox1_Enter。

Button[] buttons = null;  // Initialize somewhere with all the buttons.

void OnButtonClick(object sender, EventArgs e)
{
    for (int index = 0; index < buttons.Length; index++)
    {
        if (buttons[index] == sender)
        {
            buttons[index].Enabled = buttons[index].Visible = false;
        }
        else
        {
            buttons[index].Enabled = buttons[index].Visible = true;
        }
    }
}

抱歉,我想念您的帖子。按顺序排列

Button[] buttons = null;
        void OnButtonClick(object sender, EventArgs e)
        {
            int buttonIndex = Array.IndexOf(buttons, sender);
            for (int index = 0; index < buttons.Length; index++)
            {
                if (index == buttonIndex + 1)
                {
                    buttons[index].Enabled = buttons[index].Visible = true;
                }
                else
                {
                    buttons[index].Enabled = buttons[index].Visible = false;
                }
            }
        }

答案 1 :(得分:0)

检查每个按钮属性中每个按钮的初始值。

最好在更改按钮之前使用初始化程序设置按钮的属性。

答案 2 :(得分:0)

请勿将代码放在Enter的{​​{1}}事件中,此事件的groupoBow为GroupBox。订阅其中一个按钮的sender事件,并最终使用相同的生成方法来订阅其他2个按钮的ButtonPressed事件(如果要在编写时使用ButtonPressed语句)

答案 3 :(得分:-1)

也许你应该这样试试:

private void groupBox1_Enter(object sender, EventArgs e)
{
    Button btn = sender as Button;

    if (btn == button1)
    {
        button1.Enabled = false;
        button2.Enabled = true;
        button3.Enabled = false;
        MessageBox.Show("button 1 is disabled");
    }
    else if (btn == button2)
    {
        button1.Enabled = false;
        button2.Enabled = false;
        button3.Enabled = true;
        MessageBox.Show("button 1 & button 2 are disabled");
    }
    else if (btn == button3)
    {
        button1.Enabled = false;
        button2.Enabled = false;
        button3.Enabled = false;
        MessageBox.Show("button 3 disabled");
    }
}

这是你认为它必须工作的方式还是我弄错了?