2012-06-18 120 views
1

我做错了什么?我有一个CheckBoxList,我想逐个处理每个元素。我在“cbl.Items.Count”行出现错误,提示该元素未用“new”初始化。非常感谢你!“For循环”检查CheckBoxList的元素

CheckBoxList cbl = (CheckBoxList)FindControl("CBL_categ"); 
for (int i = 0; i < cbl.Items.Count; i++) 
{ 
    if (cbl.Items[i].Selected) 
     catn = cbl.Items[i].Value; 
} 

编辑:

<asp:Content ID="Content4" runat="server" 
    contentplaceholderid="ContentPlaceHolder3"> 
    <asp:Label ID="statusLabel" runat="server" Text=""> </asp:Label> 

    <asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server" 
    DataSourceID="SqlDataSource1" Visible="False" > 
     .... 

    </asp:GridView> 


    <br /> 
    Categories:<asp:CheckBoxList ID="CBL_categ" runat="server" DataTextField="name" DataValueField="name"> 
    </asp:CheckBoxList> 

</asp:Content> 
+6

你检查,看它是否真正找到了控制? –

回答

0

你在那里需要一个错误检查,因为它可能会返回null。

CheckBoxList cbl = (CheckBoxList)FindControl("CBL_categ"); 

if (cbl != null) 
{ 
     for (int i = 0; i < cbl.Items.Count; i++) 
     { 
      if (cbl.Items[i].Selected) 
      { 
       catn = cbl.Items[i].Value; 
      } 
     } 
} 
+1

你说得对,谢谢。该控件未找到。如果我添加(cbl!= null),则不返回错误。我怎样才能确保它找到它。该复选框列表直接放置在占位符上。 – Sam

+0

检查您的拼写是否正确。如果你有,那么我会建议在你的代码中放置一个断点并逐行逐行。不要忘记选择这个作为你接受的答案:) –

+0

谢谢!拼写是正确的。不知道如何使用断点。是否有可能让消息框出现在不同时间检查不同元素的值? – Sam

2

一个常见的原因是,如果CheckBoxList的你正在寻找嵌套一些其他容器中,FindControl已找不到它,因为它不递归搜索而会返回null。

如果嵌套,最好的性能解决方案是这样的:

FindControl("nestingcontrol").FindControl("CBL_categ") 

另外,编写运行在每个控制的FindControl递归方法,但预计影响性能。

参考:

http://forums.asp.net/t/1107107.aspx