views:

425

answers:

3

Hi all,

Is there a way to access the field header name of a databound repeater within the header template. So insted of this....

                      <HeaderTemplate>
                          <table >
                              <th ></th>
                              <th >Forename</th>
                              <th >Surname</th>
                              <th >work email</th>
                              <th ></th>
                      </HeaderTemplate>

     We get something like this.                 

                      <HeaderTemplate>
                          <table >
                              <th ></th>
                              <th ><%# Eval("Forename").HeaderName%></th>
                              <th ><%# Eval("SureName").HeaderName%></th>
                              <th ><%# Eval("WorkEmail").HeaderName%></th>
                              <th ></th>
                      </HeaderTemplate>
+1  A: 

You cannot use the <%# %> syntax in the HeaderTemplate because you it is not in a databinding scenario. You should however be able to use <%= %> and then put some method on your page/usercontrol that returns the Header.

veggerby
+1  A: 

You could move the table header into your ItemTemplate like this:

<ItemTemplate>
    <asp:Panel runat="server" Visible='<%# Container.DisplayIndex == 0 %>'>
        <tr>
            <th><%# Eval("Forename").HeaderName %></th>
        </tr>
    </asp:Panel>
    <tr>
        <td><%# Eval("Forename") %></td>
    </tr>
</ItemTemplate>

although this is slightly wasteful since the header would be bound for each row (only the first shown though). Perhaps it would be better to use <% if (...) %> instead of a Panel but I don't know how to access the Container.DisplayIndex in that context.

Per Erik Stendahl
+2  A: 

Trying to do Eval("Field").Property in the header template would throw a null exception.

I would do something like this...

Code Behind

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<SomeData> data = new List<SomeData>();

        data.Add(new SomeData("Bob"));
        data.Add(new SomeData("Joe"));

        Repeater1.DataSource = data;
        Repeater1.DataBind();
    }

    public String FirstnameColumn {
        get { return "Firstname";  } 
    }
}

public class SomeData
{
    public String Firstname { get; set; }

    public SomeData(String firstname) {
        this.Firstname = firstname;
    }
}

Markup

<table>
    <asp:Repeater ID="Repeater1" runat="server">
        <HeaderTemplate>
            <tr><td><%= FirstnameColumn %></td></tr>
        </HeaderTemplate>
        <ItemTemplate>
            <tr><td><%# Eval("Firstname") %></td></tr>
        </ItemTemplate>
    </asp:Repeater>        
</table>
Chalkey