我在文本框中有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";
}
答案 0 :(得分: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();
}
您不需要将布尔值与true / false进行比较。直接使用这些值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();
}
答案 1 :(得分: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;
}