I have a repeater on my page:
<asp:Repeater id="attachmentsRepeater" runat="server">
<HeaderTemplate>
<%
if (attachmentsRepeater.Items.Count > 0) {
if (attachmentsRepeater.Items.Count == 1) {
Response.Write("<h3>Attachment</h3>");
Response.Write("<p>");
} else {
Response.Write("<h3>Attachments</h3>");
Response.Write("<ul>");
}
}
%>
</HeaderTemplate>
<ItemTemplate>
<%# OutputAttachment(Container)%>
</ItemTemplate>
<FooterTemplate>
<%
if (attachmentsRepeater.Items.Count > 0) {
if (attachmentsRepeater.Items.Count == 1) {
Response.Write("</p>");
} else {
Response.Write("</ul>");
}
}
%>
</FooterTemplate>
</asp:Repeater>
The original ItemTemplate code looked like this:
<ItemTemplate>
<%
if (attachmentsRepeater.Items.Count > 0) {
if (attachmentsRepeater.Items.Count > 1) {
Response.Write("<li>");
}
%>
<a href="<%# DataBinder.Eval(Container.DataItem, "location") %>">
<%# DataBinder.Eval(Container.DataItem, "name") %>
</a>
<%
if (attachmentsRepeater.Items.Count > 1) {
Response.Write("<li>");
}
}
%>
</ItemTemplate>
In the codebehind, I would like to access the number of Items in the Repeater (line 4):
public string OutputAttachment(RepeaterItem Container) {
string returnValue = "";
Repeater ContainerParent = (Repeater)Container.Parent;
if (attachmentsRepeater.Items.Count > 0) {
if (attachmentsRepeater.Items.Count > 1) {
returnValue += "<li>";
}
returnValue += "<a href=\"" + DataBinder.Eval(Container.DataItem, "location");
if (DataBinder.Eval(Container.DataItem, "location").ToString().EndsWith("/")) {
returnValue += DataBinder.Eval(Container.DataItem, "name");
}
returnValue += ">" + DataBinder.Eval(Container.DataItem, "name") + "</a>";
if (attachmentsRepeater.Items.Count > 1) {
returnValue += "</li>";
}
}
return returnValue;
}
The code that is output is
<h3>Attachment</h3>
<p> </p>
From this output I know that Item.Count == 1 since there is output, the H3 is singular and there is a P tag. If Item.Count > 1, H3 would be plural and there would be a UL tag.
Is this codebehind method being run before the data is bound? Any workarounds for this? Thanks for your help.
This was working for me before, but I had to change it to fulfill a new requirement, which is when it stopped working.
The best place to do your data binding is in the code behind in the page_load event or some other event that is fired when the page is first created.
That way you can control when the data is bound - and you can call the OuputAttachment method after you have bound your data - and you can be sure that the data actually exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With