Reputation: 558
i am trying access an asp label within an asp repeater from my code behind file. here is what i have done so far :
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="LinqDataSource1" OnItemDataBound="outerFunction">
<HeaderTemplate>
<h1>Questions And Answers</h1>
</HeaderTemplate>
<ItemTemplate>
<p style="background-color:Red; color:Yellow;"><%#Eval("QText") %> :::::::::</p>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# setQID(Eval("QID"))%>' />
<asp:Label ID="pageLabel" runat="server" Text="Label"></asp:Label>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="LinqDataSource2">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<%# (GetAnswer(Eval("AnsQID"))) != 1 ? (displayAnswer(Eval("AText"))) : ""%>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
<span style="display:block; border-top:1px solid Gray;"></span>
</ItemTemplate>
</asp:Repeater>
*Here is my code behind *
public void outerFunction(object sender, RepeaterItemEventArgs e)
{
Label myLabel = (Label) e.Item.FindControl("pageLabel");
myLabel.Text = "HELLO World";
}
I am trying to display Questions and Answers. For every question there can be multiple answers. That is why i have it in a nested repeater control. For now I just need to know how i can have say for example have a "div" element in the outer repeater and bind every answer i get within the inner repeater to that parent div.
Thanks !
Upvotes: 3
Views: 3363
Reputation: 44595
the way you are doing right now is not safe when the currently processed item is the header or footer, label is in ItemTemplate
so will be available only for the DataItems, try like this:
public void outerFunction(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label myLabel = (Label) e.Item.FindControl("pageLabel");
myLabel.Text = "HELLO World";
}
}
Upvotes: 0
Reputation: 10123
Since you have a header template that does not contain a "pageLabel", you'll get a null reference error when that portion of the repeater is data bound.
Put the label portion in an if block:
if (e.Item.ItemType == ListItemType.Item)
{
...
}
If you use the AlternatingItemTemplate, you'll also want to include that:
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
...
}
Upvotes: 1
Reputation: 63970
Your code looks good except that you are not checking the type of row you are in:
public void outerFunction(object sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
Label myLabel = (Label) e.Item.FindControl("pageLabel");
myLabel.Text = "HELLO World";
}
}
Upvotes: 9