读书人

求一段简单代码,该如何解决

发布时间: 2012-03-06 20:47:55 作者: rapoo

求一段简单代码
有一组复选按钮,id为CB1到CB6,将某些选中后提交其text值给一个label,如何循环实现?
string str= " ";
for (int i = 1; i <= 6; i++)
{
str += ((CheckBox)FindControl( "CB " + i)).Text;
}
再赋给label时就会有错误
帮忙下


[解决办法]
什么错误???说清楚一点!
[解决办法]
是不是checkbox没有了,找不到了???用的进修判断一下.CheckBox chk= (CheckBox)FindControl( "CB " + i);if(chk != null){ str += chk.Text;}
[解决办法]
用慕白兄的方法不会出现运行错误,但text值添加不到label======> 因为没有checkbox所以添加不上
[解决办法]
如果是VS05的话可以用CheckBoxList控件,直接按索引器访问多选框的每项,不会引发NullReferenceException.
VS03的话还是老老实实一个一个的判断是否选中吧
[解决办法]
用CheckBoxList的
//aspx
<form id= "Form1 " method= "post " runat= "server ">
<asp:CheckBoxList id= "CheckBoxList1 " runat= "server " RepeatDirection= "Horizontal ">
<asp:ListItem Value= "aa "> aa </asp:ListItem>
<asp:ListItem Value= "bb "> bb </asp:ListItem>
<asp:ListItem Value= "cc "> cc </asp:ListItem>
</asp:CheckBoxList>
<asp:Button id= "Button1 " runat= "server " Text= "Button "> </asp:Button>
<asp:Label id= "Label1 " runat= "server "> </asp:Label>
</form>

//aspx.cs
private void Button1_Click(object sender, System.EventArgs e)
{
string str = string.Empty;
for(int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if(CheckBoxList1.Items[i].Selected)
str += CheckBoxList1.Items[i].Text;
}
Label1.Text = str;
}
[解决办法]
用CheckBox的
//aspx
<asp:checkbox id= "CheckBox1 " runat= "server " Text= "aa "> </asp:checkbox>
<asp:checkbox id= "CheckBox2 " runat= "server " Text= "bb "> </asp:checkbox>
<asp:checkbox id= "CheckBox3 " runat= "server " Text= "cc "> </asp:checkbox> <br>
<asp:button id= "Button1 " runat= "server " Text= "Button "> </asp:button>
<asp:label id= "Label1 " runat= "server "> </asp:label>

//aspx.cs
private void Button1_Click(object sender, System.EventArgs e)
{
string str = string.Empty;
for (int i = 1; i <= 3; i++)
{
CheckBox ck = (CheckBox)FindControl( "CheckBox " + i);
if(ck.Checked)
str += ck.Text;
}
Label1.Text = str;
}

读书人网 >asp.net

热点推荐