Injecting table row inside repeater item

回眸只為那壹抹淺笑 提交于 2019-12-10 18:43:41

问题


I am trying to inject inside repeaters items, the problem is that the row is generated in a wrong location.
If you try this simple example, you will see that the rown is generated under label '2' as it should be generated under label '1'.

Why does it happen? And how to fix that?

protected void Page_Load(object sender, EventArgs e)
{
    int [] array = {1,2,3,4,5};
    rpt.DataSource = array;
    rpt.DataBind();     
}

protected string _extraRowHtml;
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Item ||
          e.Item.ItemType == ListItemType.AlternatingItem)
  {           
       int tmp = ((int)e.Item.DataItem);
       _extraRowHtml = tmp == 1 ? "<tr><td class=\"topicsRow\" colspan=\"100%\"> Topics </td></tr>" : string.Empty; ;                

  }
}

<asp:Repeater ID="rpt" runat="server" onitemdatabound="rpt_ItemDataBound">
    <HeaderTemplate>
       <table  cellpadding="0px" cellspacing="0">             
    </HeaderTemplate>            
    <ItemTemplate>     
      <tr style="height:50px">            
        <td>  

          <asp:HyperLink  ID="lnkTitle" runat="server" Text='<%# Container.DataItem%>'/>              
         </td>              
       </tr>
       <%# _extraRowHtml %>   
    </ItemTemplate>        
  <FooterTempl
    </table> 
  </FooterTemplate> 
</asp:Repeater>

回答1:


Personally I think a better way of doing is is to replace:

<%# _extraRowHtml %>

with

<%# GetExtraRow(Container.DataItem) %>

then in your code behind implement:

protected string GetExtraRow(object Data)
{
    int tmp = (int) Data:
    return _tmp == 1 ? 
        "<tr><td class=\"topicsRow\" colspan=\"100%\"> Topics </td></tr>" : 
        string.Empty;
}

Then and get rid of the rpt_ItemDataBound function (and the onItemDataBound).




回答2:


Doing things this way is going to be prone to error, as using a variable in this manner is not something that you are going to have full control over.

What I would do is add something like the following to the template.

<asp:literal id="litExtraRow" runat="server" mode="Passthrough" />

Then in your codebehind on the item databound event

if (((int)e.Item.DataItem) == 1)
{
    ((Literal)e.Item.FindControl("litExtraRow")).Text = "Your HTML Here";
}

Something like this should be a bit more reliable.

The reason you are having issues is that the template is evaluated with the values as they are as "ItemDataBound" has been called, and row 1, the value is string.Empty, and then for the second row, you updated it after item 1 was databound.



来源:https://stackoverflow.com/questions/2600633/injecting-table-row-inside-repeater-item

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