单击另一个按钮时尝试使按钮显示某些内容(C#)

时间:2015-09-15 14:47:38

标签: c# winforms

我使用的是Windows Forms Application,语言为C#。我创建了5个按钮,3个标签将显示文本。门锁,门解锁,狗回家,狗不在家,显示风险=是按钮的名称。 我想要做的是显示门被解锁的风险和狗不在家,因为盗贼很容易闯入。我被困在Show Risk按钮,因为我不知道如何使用如果声明并告诉按钮如果解锁门和狗不是主页按钮被点击然后显示“小偷可能会闯入房子”

public partial class Form1 : Form { public Form1() { InitializeComponent(); }

    private void btLock_Click(object sender, EventArgs e)
    {
        lbDoor.Text = "Door is now locked!";
    }

    private void btUnlock_Click(object sender, EventArgs e)
    {
        lbDoor.Text = "Door is now unlocked!";
    }

    private void btDogIsHome_Click(object sender, EventArgs e)
    {
        lbDog.Text = "Dog is home!";
    }

    private void btDogIsNotHome_Click(object sender, EventArgs e)
    {
        lbDog.Text = "Dog is not home!";
    }

    private void btShowRisk_Click(object sender, EventArgs e)
    {    
        if ()
        {
            lbDisplayRisk.Text = "Thieves might break into the house!";
        }
        else 
        {
            lbDisplayRisk.Text = "The house is secure!";
        }
    }
}

2 个答案:

答案 0 :(得分:0)

以下是如何通过引入布尔来表示门的状态(锁定或解锁)来添加状态:

class SecuritySystem {
    // this variable maintains the state of the door
    private boolean doorLocked;

    // door lock click event handler
    private void btLock_Click(object sender, EventArgs e) {
        doorLocked = true;
        lbDoor.Text = "Door is now locked!";
    }

    // door unlock click event handler
    private void btUnlock_Click(object sender, EventArgs e) {
        doorLocked = false;
        lbDoor.Text = "Door is now unlocked!";
    }
}

知道这一点,你能弄清楚如何维持狗的状态吗? (提示,它的方式是一样的!)

现在你已经拥有了Dog and the Door的状态,你能否在风险的if声明中找出你需要写的内容? (仅供参考,您在if语句中输入的逻辑测试称为谓词。)

由于您有两个二元结果,因此总共有四个案例需要考虑:

  1. 门解锁,狗不在家(00)
  2. 门在家解锁和狗(01)
  3. 门锁和狗不在家(10)
  4. 家里的门锁和狗(11)
  5. 右边的数字代表:[门状态 - 0 =解锁; 1 =已锁定] [狗国 - 0不在家; 1 =在家里]

答案 1 :(得分:0)

public partial class Form1 : Form { public Form1() { InitializeComponent(); }

private bool isDoorLocked =true;
private bool isDogHome =true;
private void btLock_Click(object sender, EventArgs e)
{
    lbDoor.Text = "Door is now locked!";
    isDoorLocked = true;

}

private void btUnlock_Click(object sender, EventArgs e)
{
    lbDoor.Text = "Door is now unlocked!";
    isDoorLocked = false;
}

private void btDogIsHome_Click(object sender, EventArgs e)
{
    lbDog.Text = "Dog is home!";
    isDogHome= true;
}

private void btDogIsNotHome_Click(object sender, EventArgs e)
{
    lbDog.Text = "Dog is not home!";
    isDogHome = false;
}

private void btShowRisk_Click(object sender, EventArgs e)
{    
    if (!isDogHome && !isDoorLocked )
    {
        lbDisplayRisk.Text = "Thieves might break into the house!";
    }
    else 
    {
        lbDisplayRisk.Text = "The house is secure!";
    }
}
}