我是C#的初学者,我有一份家庭作业。在表单中,我有一个带有5个单选按钮和数字上/下数天的组合框。当我改变数量。上下,背景颜色应该改变之前选择的颜色。我只能使用switch-case。我管理了这个数字。上下,标签随之变化。但我无法插入开关盒以换色。实际上我无法命名开关。
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "Pazartesi";
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
byte sayi = Convert.ToByte(numericUpDown1.Value);
switch (sayi)
{
case 1:
label1.Text="Pazartesi";
switch ( )
{
case renkbtn_1.Checked:
this.BackColor = Color.Red;
break;
case renkbtn_2.Checked:
this.BackColor = Color.White;
break;
case renkbtn_3.Checked:
this.BackColor = Color.Yellow;
break;
case renkbtn_4.Checked:
this.BackColor = Color.Blue;
break;
case renkbtn_5.Checked:
this.BackColor = Color.Green;
break;
}
break;
case 2:
label1.Text="Salı";
break;
case 3:
label1.Text = "Çarşamba";
break;
case 4:
label1.Text = "Perşembe";
break;
case 5:
label1.Text = "Cuma";
break;
case 6:
label1.Text = "Cumartesi";
break;
case 7:
label1.Text = "Pazar";
break;
答案 0 :(得分:2)
switch语句不起作用。
switch ( )
中的大括号内应该是一个表达式,它会产生一些值(它的不是一个'name',但可能是一个变量)。
那些case
必须具有(编译时)常量,这些常量将根据switch表达式中的值进行检查。
您必须将其重写为一堆if
语句:
if (renkbtn_1.Checked)
this.BackColor = Color.Red;
else if (renkbtn_2.Checked)
this.BackColor = Color.White;
else if (renkbtn_3.Checked)
this.BackColor = Color.Yellow;
else if (renkbtn_4.Checked)
this.BackColor = Color.Blue;
else if (renkbtn_5.Checked)
this.BackColor = Color.Green;
答案 1 :(得分:0)
如果我理解了这个问题,你可以改变上下值,你想要将背景颜色设置为你选择的无线电按钮的颜色。正确?
如果是这种情况,你必须检查哪个radiobutton然后正确设置颜色。
然后,您可以遍历组框的控件以获取已检查的广播:
foreach (Control c in groupBox1.Controls)
{
if (c.GetType() == typeof(RadioButton))
{
RadioButton rb = c as RadioButton;
if (rb.Checked)
{
//here you can either store the checked radio button in a variable to further check the color you need to set, or do the logic here.
}
}
}
}
您的整个代码可能是这样的:
private void Form1_Load(object sender,EventArgs e) { label1.Text =“Pazartesi”;
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
byte sayi = Convert.ToByte(numericUpDown1.Value);
switch (sayi)
{
case 1:
label1.Text="Pazartesi";
break;
case 2:
label1.Text="Salı";
break;
case 3:
label1.Text = "Çarşamba";
break;
case 4:
label1.Text = "Perşembe";
break;
case 5:
label1.Text = "Cuma";
break;
case 6:
label1.Text = "Cumartesi";
break;
case 7:
label1.Text = "Pazar";
break;
}
RadioButton selectedRadio = GetSelectedRadioButton();
switch(selectedRadio.Name)
{
case rankbtn_1.Name:
this.BackColor = Color.Red;
break;
case rankbtn_2.Name:
this.BackColor = Color.White;
break;
//Repeat for the other buttons.
}
}
private RadioButton GetSelectedRadioButton()
{
foreach (Control c in groupBox1.Controls)
{
if (c.GetType() == typeof(RadioButton))
{
RadioButton rb = c as RadioButton;
if (rb.Checked)
{
return rb;
}
}
}
}