views:

206

answers:

2

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  A: 

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.

Mitchel Sellers
I don't want to have a special serve control (asp:literal) for that, because the rown should be generated once... so I don't want the controls to appear in the control tree of he page
nemiss
+2  A: 

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).

Keltex