我想创建一个切换按钮,但它保持打开状态。如何将按钮从打开切换为关闭。

private void Form2_Load(object sender, EventArgs e){

    Button button = new Button();
    button.Location = new Point(200, 30);
    button.Text = "Off";
    this.Controls.Add(button);

    if (button.Text != "On")
    {
        button.Text = "On";
        button.BackColor = Color.Green;
    }
    else if (button.Text == "On")
    {
        button.Text = "On";
        button.BackColor = Color.Red;
    }
}

最佳答案

您需要将代码更改为在按钮的Click事件处理程序中更改按钮的外观:

private void Form2_Load(object sender, EventArgs e){

    Button button = new Button();
    button.Location = new Point(200, 30);
    button.Text = "Off";
    this.Controls.Add(button);

    // subscribe to the Click event
    button.Click += button_Click;
}

// the Click handler
private void button_Click(object sender, EventArgs e)
{
    Button button = sender as Button;
    if (button == null) return;

    if (button.Text != "On")
    {
        button.Text = "On";
        button.BackColor = Color.Green;
    }
    else if (button.Text == "On")
    {
        button.Text = "Off";
        button.BackColor = Color.Red;
    }
}


请注意,在您的else块中,您设置了错误的文本。将其更改为"Off"

关于c# - 开关按钮保持在开,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37440411/

10-12 00:01
查看更多