Why is the footer-item not included in Repeater.Items?

时光总嘲笑我的痴心妄想 提交于 2019-12-22 06:53:46

问题


I need to get a value from a textbox inside a FooterTemplate in the OnClick event of a button. My first thought was to loop through the items-property on my repeater, but as you can see in this sample, it only includes the actual databound items, not the footer-item.

ASPX:

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        Item<br />
    </ItemTemplate>
    <FooterTemplate>
        Footer<br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:Repeater>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

Code-behind.cs:

protected void Page_Load(object sender, EventArgs e)
{
    ListItemCollection items = new ListItemCollection();
    items.Add("value1");
    items.Add("value2");
    Repeater1.DataSource = items;
    Repeater1.DataBind();
}

protected void Button1_Click(object sender, EventArgs e)
{
    System.Diagnostics.Debug.WriteLine(Repeater1.Items.Count);
}

This code will only output "2" as the count, so how do I get to reference my textbox inside the footertemplate?


回答1:


From the MSDN documentation, the Items is simply a set of RepeaterItems based off the DataSource that you are binding to and does not include items in the Header or FooterTemplates.

If you want to reference the textbox, you can get a reference on ItemDataBound event from the repeater where you can test for the footer.

E.g.

private void Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e) 
{

  if (e.Item.ItemType == ListItemType.Footer) 
  {
    TextBox textBox = e.Item.FindControl("TextBox1") as TextBox;
  }
}    



回答2:


You can find controls in the repeater. That will give you all the controls in the repeater (RepeaterItems collection). Now you can do something like this:

RepeaterItem footerItem=null;
foreach(Control cnt in Repeater1.Controls)
{
if(cnt.GetType() == typeof(RepeaterItem) && ((RepeaterItem)cnt).ItemType == ListItemType.Footer)
{
footerItem = cnt;
break;
}
}



回答3:


The footer should be the last child control of the repeater so you can do something like..

RepeaterItem riFooter = Repeater1.Controls[Repeater1.Controls.Count - 1] as RepeaterItem;
if (riFooter != null && riFooter.ItemType == ListItemType.Footer) {
    TextBox TextBox1 = riFooter.FindControl("TextBox1") as TextBox;
    if (TextBox1 != null) {
        TextBox1.Text = "Test";
    }
}


来源:https://stackoverflow.com/questions/495597/why-is-the-footer-item-not-included-in-repeater-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!