从代码隐藏中的中继器获取值

本文关键字:中继器 获取 代码 隐藏 | 更新日期: 2023-09-27 18:24:35

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="EntityDataSourceTeklifler">
     <ItemTemplate>
          <div class="panel panel-primary">
               <div class="panel-body">
                    <strong>Teklif Kodu:</strong>&nbsp;<%#Eval("TeklifId") %><br />
                    <strong>Teklif Tarihi:</strong>&nbsp;<%#Eval("TeklifTarih") %><br />
                    <strong>Teklifi Hazırlayan:</strong>&nbsp;<%#Eval("Name") %>&nbsp;<%#Eval("Surname") %><br />
                    <strong>Firma Adı:</strong>&nbsp;<%#Eval("FirmaAdi") %><br />
                    <strong>Sipariş:</strong>&nbsp;<%#Eval("FUrunId") %><br />
                    <strong>Teklif Tutarı:</strong>&nbsp;<%#Eval("TeklifTutar") %><br />
               </div>
          </div>
    </ItemTemplate>
</asp:Repeater>

如您所见,我有一个Repeater,它可以毫无问题地显示我的数据。我需要在代码隐藏中访问TeklifId。我将做一些类似的东西:

if(TeklifId == 1)
{
  //do something
}
else if(TeklifId == 2)
{
  //do something else
}

为此,我需要在它添加到Repeater时获得所有TeklifId

从代码隐藏中的中继器获取值

理想情况下,您应该在标记中包含一些 ASP.NET 控件(如Label, Textbox控件(中的数据ItemTemplate因为使用它们很容易。但我不确定为什么要直接添加普通的 html 标签。

无论如何,要找到该值,您必须在中继器控件的ItemDataBound控件中找到它,但为此,您必须通过添加如下所示runat="server"属性来使strong标记为服务器控件:-

<strong id="TeklifId" runat="server">Teklif Kodu:</strong>&nbsp;<%#Eval("TeklifId") %>

然后,在重复控件中添加 ItemDataBound 事件,如下所示:

<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand"

最后在后面的代码中,您可以找到这样的值:-

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.AlternatingItem || 
       e.Item.ItemType == ListItemType.Item)
    {
       HtmlGenericControl TeklifId = e.Item.FindControl("TeklifId") as HtmlGenericControl;
       string TeklifId = TeklifId.InnerText;  //value here
    }
}

TeklifId放在Label控件中,以便可以使用IDFindControl来获取如下所示的值:

<asp:Label ID="TeklifId" runat="server" Text='<%#Eval("TeklifId") %>'></asp:Label>

然后:

foreach (RepeaterItem item in Repeater1.Items)
{
     var TeklifId = (Label)item.FindControl("TeklifId");
     if (TeklifId == 1)
     {
         //do something
     }
}

中继器代码:

<td>
   <span runat="server" id="lbBranchname" style="font-style:italic;"><%# Eval("branchname")%></span>
</td>

代码隐藏 : rptBranch_ItemCommand

HtmlGenericControl lbBranchname = e.Item.FindControl("lbBranchname") as HtmlGenericControl;
BranchName = lbBranchname.InnerText;