读书人

图形界面上如果单选框没有操作就提

发布时间: 2013-06-19 10:26:41 作者: rapoo

图形界面上,如果单选框没有操作,就提示“请选择”,应该如何写
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("你已经选择了一个选择项!");
}
}


[解决办法]
用panel容器 foreach遍历一下control就行
[解决办法]
创建一个类
publi class aaaa
{
privoid radioButton ra=null;
privoid string str="";//你选择了A,你选择了B ...
privoid string x=""//选择对,选择错
剩下的封装自己写
}

然后
IList<aaaa> iList=new List<aaaa>();
iList.add(new aaaa(){ra=radioButton1,str="你选择A",x="你选择对了"});
iList.add(new aaaa(){ra=radioButton2,str="你选择B",x="你选择错了"});
iList.add(new aaaa(){ra=radioButton3,str="你选择B",x="重选"});

radioButton1.Checked +=radioButton_CheckedChanged;
radioButton2.Checked +=radioButton_CheckedChanged;
radioButton3.Checked +=radioButton_CheckedChanged;


private void radioButton_CheckedChanged(object sender, EventArgs e)
{
for(int i=0;i<iList.length;i++)
{
if (iList[i].ra.Checked==true)
{
label1.Text = iList[i].str;
}
}
}

private void button1_Click(object sender, EventArgs e)
{
if (radioButton3.Checked)
{
MessageBox.Show(iList[i].str);
return;
}

for(int i=0;i<iList.length;i++)
{
if(iList[i].ra.Checked==false)
{
MessageBox.Show("请选择");
}else if MessageBox.Show("答错了");
}
}

读书人网 >C#

热点推荐