15

If I have a List < Person > where person is defined by the class

class Person
{
   string Forename
   {
      get;set;
   }
   string Surname
   {
      get; set;
   }
}

And I bind it to an asp repeater control that looks like this:

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:Label ID="lblForename" runat="server" Text="Forname" AssociatedControlID="txtForename" />
        <asp:TextBox ID="txtForename" runat="server" Text='<%# ((Person)Container.DataItem).Forename %>' />
        <br />
        <asp:Label ID="lblSurname" runat="server" Text="Forname" AssociatedControlID="txtSurname" />
        <asp:TextBox ID="txtSurname" runat="server" Text='<%# ((Person)Container.DataItem).Surname %>' />
        <br />
    </ItemTemplate>
</asp:Repeater>

What is the best way to get the data that the user types in back into the objects?

I thought that the whole point of data binding was that this was effectively handled for you, but when I inspect the Repeater1.Items collection, there are no changes made. Do I have to write code to do something along the lines of

//This is only intended to be pseudo code
for each item in Repeater1.Items
    ((Person)item.DataItem).Forename = item.FindControl("txtForname").Text;
end for

If that is the case, why is the DataItem property always empty?

Additional info:

I am already calling code the the effect of

this.Repeater1.DataSource =  this.PersonList;
this.Repeater1.DataBind();

I've tried using Bind("Forename"), but this doesn't seem to bring the info from the TextBox back into the object, do I have to do this manually?

4

3 回答 3

8

简单的答案是Repeater 控件不支持您正在寻找的那种双向数据绑定。最重要的是,DataItem 属性仅在创建中继器项目期间使用,并且在 ItemDataBound 事件之后,它被设置为空。因此,您不能使用该属性来获取回发后创建特定转发器项目时使用的原始对象(就像您在伪代码中所做的那样)。

您将必须按照您的建议遍历中继器项目(确保在执行任何操作之前检查该项目是 ListItemType.Item 还是 AlternatingItem),然后从文本框中提取值并在更新中使用它们。

于 2009-05-14T17:10:19.967 回答
7

如果您将中继器与您想要的人员列表绑定

this.Repeater1.DataSource =  GetPersons();

而 GetPersons() 是一种返回您可以使用的人员对象列表的方法

<asp:TextBox ID="txtForename" runat="server" Text='<%# Eval("Forename") %>' />
于 2009-05-14T16:03:35.777 回答
2

除了上述之外,还需要将repeater绑定到List。现在,文本框被分配给 Forename 的值(或者如果您使用

<# Bind("Forename") %>

标记),但中继器容器没有数据项。

于 2009-05-14T15:57:01.440 回答