adding multiple <asp:Hyperlink>s into a repeater
- by Colin Pickard
I have a repeater control, and I want to put an unknown number of <asp:Hyperlink>s into the template, for example if you start with this:
<asp:Repeater runat="server" ID="PetsRepeater">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "Owner")%>
<%#this.ListPets(Container.DataItem)%>
</ItemTemplate>
</asp:Repeater>
and in code behind:
public partial class test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PetOwner p = new PetOwner() {
Owner = "Jimmy",
PetNames = new List<String>() { "Nemo", "Dory" }
};
List<PetOwner> PetOwners = new List<PetOwner>() { p };
PetsRepeater.DataSource = PetOwners;
PetsRepeater.DataBind();
}
}
protected String ListPets(Object PetOwner)
{
StringBuilder sb = new StringBuilder();
foreach (String Name in ((PetOwner)PetOwner).PetNames)
{
if (sb.Length > 0) sb.Append(", ");
sb.Append(Name);
}
return sb.ToString();
}
}
class PetOwner
{
public String Owner;
public List<String> PetNames;
}
Now suppose instead of having the string "Nemo, Dory" in my repeater, I want something like this:
<asp:HyperLink runat=server Text="Nemo" NavigateUrl="Pet.aspx?Name=Nemo" />,
<asp:HyperLink runat=server Text="Dory" NavigateUrl="Pet.aspx?Name=Dory" />
How can I do that? I tried putting a foreach inline in the aspx page, but I get the error Invalid expression term 'foreach'.