views:

62

answers:

2

What is the right way to do this in a datarepeater control?

                <asp:Repeater ID="Repeater1" runat="server">
                <ItemTemplate>
                <strong><%= Eval("FullName") %></strong><br />
                <p>
                <%= Eval("Summary") %>
                </p>
                </ItemTemplate>
                </asp:Repeater>

Getting error Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

I'd like to just write out the FullName and Summary. But I don't want to nest subcontrols. Is Repsonse.Write the best way?

UPDATE: Not sure if this is necessary, but the only way I was able to solve it was with controls

+3  A: 

The repeater requires a datasource, assigned like so:

public class Foo
{
public string FullName { get;set; } 
public string Summary {get;set; }

public Foo(fullName,summary)
{
  FullName=fullName;
  Summary=summary;
}
}

/// elsewhere...
List<Foo> myFoos = new List<Foo>();
myFoos.Add(new Foo("Alice","Some chick"));
myFoos.Add(new Foo("Bob","Some guy"));
myFoos.Add(new Foo("Charlie","Indeterminate"));
Repeater1.DataSource = myFoos;
Repeater1.DataBind();

As this example shows, your datasource can be anything that implements IEnumerable - lists are my favorites, but most collections in C# fall into this category. Your datasource does not have to come from a database or anywhere particular.

You don't have to use response.write, or subcontrols. (server controls aren't valid inside of a repeater, anyway). You might try replacing

<%=Eval("...

with

<%#Eval("...

I'm unsure of the difference, but the second form is used in most examples.

David Lively
Replacing <%= with <%# will solve the problem. If the control doesn't have a datasource it just won't output anything.
Mike L
with <%=Eval I get the error - Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control. with <%# Argument type System.String is not assignable to parameter type string.weird
tyndall
Post your modified markup.
David Lively
A: 

You can always try the follow:

 <%# DataBinder.Eval(Container.DataItem, "FullName") %>
Chris
That gives me an error. You can't use the DataBinder outside of a DataBound control?
tyndall
Are you not binding your repeater to a datasource somewhere?
Chris