在转发器项目中注入表行

时间:2010-04-08 14:19:23

标签: asp.net repeater

我正在尝试注入内部转发器项目,问题是该行是在错误的位置生成的 如果你试试这个简单的例子,你会发现rown是在标签'2'下生成的,因为它应该在标签'1'下生成。

为什么会这样?以及如何解决这个问题?

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>

2 个答案:

答案 0 :(得分:3)

我个人认为更好的做法是替换:

<%# _extraRowHtml %>

<%# GetExtraRow(Container.DataItem) %>

然后在你的代码背后实现:

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

然后摆脱rpt_ItemDataBound函数(以及onItemDataBound)。

答案 1 :(得分:1)

以这种方式做事会容易出错,因为以这种方式使用变量并不是你可以完全控制的东西。

我要做的是在模板中添加如下内容。

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

然后在项目数据绑定事件

的代码隐藏中
if (((int)e.Item.DataItem) == 1)
{
    ((Literal)e.Item.FindControl("litExtraRow")).Text = "Your HTML Here";
}

这样的事情应该更可靠。

您遇到问题的原因是模板的评估值为“ItemDataBound”已被调用,第1行,值为string.Empty,然后第二行,您更新了它在第1项之后是数据绑定。