1

我在文本框中有 3 个带有相应消息的复选框。我的老师希望在复选框仍处于选中状态时将消息保留在文本框中,并在未选中时隐藏文本。在我的情况下,当我选中 3 个复选框时,它们的 3 个相应消息会出现,但是当我取消选中其中一个复选框并且其他两个仍处于选中状态时,所有消息都会消失。我的问题是,当我取消选中其中一个复选框并且其他 2 个仍处于选中状态时,剩余两个选中复选框的相应消息将保留在其文本框中。

private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
    if (chkCarWheels.Checked == true)
        lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
    else
        lblMessage.Text = "My  " + txtName.Text + " Car";
}

private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
    if (chkCarAcceleration.Checked == true)
       lblMessage.Text = lblMessage.Text + mycar.Accelerate();
    else
        lblMessage.Text = "My  " + txtName.Text + " Car";
} 

private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
    if (chkCarBreakpad.Checked == true)
        lblMessage.Text = lblMessage.Text + mycar.hasBreak();
    else
        lblMessage.Text = "My  " + txtName.Text + " Car";
}
4

2 回答 2

0

看起来您需要根据复选框状态创建消息。您可以创建方法,该方法将完成工作并在某些复选框的状态更改时调用它。

private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
    BuildMessage();
}

private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
    BuildMessage();
} 

private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
    BuildMessage();
}

或者更好的一个 -为所有复选框创建一个事件处理程序

// use for chkCarWheels, chkCarAcceleration, chkCarBreakpad
private void chkCar_CheckedChanged(object sender, EventArgs e)
{
    BuildMessage();
}

private void BuildMessage()
{     
    lblMessage.Text = "My  " + txtName.Text + " Car";
    if (chkCarWheels.Checked)
        lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
    if (chkCarAcceleration.Checked)
       lblMessage.Text = lblMessage.Text + mycar.Accelerate();
    if (chkCarBreakpad.Checked)
       lblMessage.Text = lblMessage.Text + mycar.hasBreak();
}

您不需要将布尔值与真/假进行比较。直接使用这些值if (chkCarWheels.Checked)。请记住,在 C# 中,我们使用 CamelCase 名称形式的方法。还考虑用于StringBuilder构建整个消息,然后将其分配给标签:

private void BuildMessage()
{
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("My {0} Car", txtName.Text);
    if (chkCarWheels.Checked)
        sb.Append(mycar.hasWheels(4));
    if (chkCarAcceleration.Checked)
       sb.Append(mycar.Accelerate());
    if (chkCarBreakpad.Checked)
       sb.Append((mycar.hasBreak());
    lblMessage.Text = sb.ToString();
} 
于 2012-12-09T17:19:13.190 回答
0

尝试这个:

    private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
    {
        chkCar();
    }

    private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
    {
        chkCar();
    } 

    private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
    {
       chkCar()
    } 



private void chkCar()
{

string msg="";

if (chkCarWheels.Checked)
msg=msg+mycar.hasWheels(4);

if(chkCarAcceleration.Checked)
msg=msg+mycar.Accelerate();

if(chkCarBreakpad.Checked)
msg=msg+mycar.hasBreak();

lblMessage.Text=msg;

}
于 2012-12-09T17:21:07.883 回答