Reputation: 3167
What am I doing wrong? I have a CheckBoxList and I want to handle each element one by one. I get an error on the "cbl.Items.Count" line suggested the element is not initialized with "new". Thanks you very much!
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;
}
EDIT:
<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>
Upvotes: 1
Views: 2847
Reputation: 1887
A common cause of this is that if the CheckBoxList you're looking for is nested inside some other container, FindControl won't find it as it doesn't search recursively and will instead return null.
If it is being nested, the best performance solution is something like:
FindControl("nestingcontrol").FindControl("CBL_categ")
Alternatively, write a recursive method that runs a FindControl on each control, but expect a performance hit.
Reference:
Upvotes: 2
Reputation: 2989
You need an error check in there because it may be returning 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;
}
}
}
Upvotes: 0