图形界面上,如果单选框没有操作,就提示“请选择”,应该如何写
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void radioButton1_CheckedChanged_1(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label1.Text = "你选择了A";
}
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
if (radioButton2.Checked)
{
label1.Text = "你选择了B";
}
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
if (radioButton3.Checked)
{
label1.Text = "你选择了C";
}
}
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
if (radioButton4.Checked)
{
label1.Text = "你选择了D";
}
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton3.Checked)
{
MessageBox.Show("恭喜答对了");
}
else if (radioButton1.Checked == false & radioButton2.Checked == false & radioButton3.Checked == false & radioButton4.Checked == false)
{
MessageBox.Show("请选择");
}
else
{
MessageBox.Show("答错了");
}
}
}
这是我可以运行的源代码, 在else if段,你们看到我的代码应该知道我的意思,虽然程度达到我的想法,但这样做肯定是最不好的吧,四个选项还好,多的时候就麻烦了,而且浪费资源,请告诉我应该怎么样写才最简洁达到目的,谢谢大家
[解决办法]
首先if判断中应该用 && 不是 &
你可以将选项的单项都放到一个容器中,比如panel中,然后你遍历这个panel的controls,判断是否有选中
[解决办法]
radioButton 放在Panel内
循环遍历
弄个变量记录是否选中 如果判断到选中了就break
最后判断
能懂不?
[解决办法]
private void button1_Click(object sender, EventArgs e)
{
Boolean findCheck = false;
foreach (Control tmpctl in Controls)
{
if (tmpctl.Text.Trim().Contains("rad"))
{
RadioButton rad = (RadioButton)(tmpctl);
{
if (rad.Checked)
{ findCheck = true;}
}
}
}
if (findCheck == false)
{
MessageBox.Show("请选择!");
return;
}
else
{
MessageBox.Show("你已经选择了一个选择项!");
}
}