如何在转发器控件中获取元素ID

时间:2014-12-26 17:37:33

标签: c# asp.net repeater

我正在创建一个社交网站,我似乎无法在后面的代码中获得“LinkEmail”,我需要这个功能,因为我然后用它来发布到数据库。

LinkEmail是在第一个转发器中动态生成的,我需要一种方法来获取该值。

目前我在浏览器中收到此错误:

编译器错误消息:CS0103: The name 'LinkEmail' does not exist in the current context

这是aspx代码

 <asp:Repeater runat="server" ID="Repeater1">
 <ItemTemplate>

     <div style="border-top: thin none #91ADDD; border-bottom: thin none #91ADDD; padding: 10px;  width: 548px; margin-top: 10px; right: 10px; left: 10px; border-left-width: thin; margin-left: 15px; background-color: #F6F6F6; border-left-color: #91ADDD; border-right-color: #91ADDD;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <br />
                    <div style="width: 58px; height: 40px">
                    <asp:Image ID="Image2" runat="server" Height="59px" ImageAlign="Top" ImageUrl="~/Profile/Image/Default.png" Width="55px" />
                        </div>
                    <div style="width: 307px;  margin-left: 65px; margin-top: -60px">
                        <asp:Label ID="Label6" runat="server" Font-Bold="True" Font-Names="Arial" ForeColor="#3b5998"><%#Eval("YourName") %> </asp:Label>
                    </div>
                    <div id="status" style=" width: 461px; margin-left: 78px; margin-top: 11px;">&nbsp;<asp:Label ID="Label7" runat="server" Font-Italic="False" ForeColor="Black" Font-Size="Medium"><%#Eval("Birthday") %> </asp:Label>

                        <asp:LinkButton ID="LinkEmail" runat="server" OnClick="lbl_Click"><%#Eval("Email") %></asp:LinkButton>
                        <asp:Button ID="Button1" runat="server" Text="Button"  />
                    </div>

                    &nbsp;
                </div>


 </ItemTemplate>

你能告诉我如何将LinkBut​​ton ID传递给我的代码隐藏文件吗?

2 个答案:

答案 0 :(得分:2)

您可以在ItemCommand事件中找到它: -

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    LinkButton LinkEmail= e.Item.FindControl("LinkEmail") as LinkButton ;
}

您需要将此事件处理程序与您的控件关联,如下所示: -

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

答案 1 :(得分:0)

foreach(RepeaterItem item in Repeater1.Items)
{
LinkButton LinkEmail=(LinkButton)item.FindControl("LinkEmail");

//Do here what ever you want

}
  

使用发件人

通过投射链接按钮RepeaterItem获得NamingContainer。然后,您可以使用FindControl来获取对其他控件的引用。

protected void lbl_Click(object sender,EventArgs e)
{
 LinkButton LinkEmail=(LinkButton)  sender;
 var RepeaterRow=(RepeaterItem)LinkEmail.NamingContainer;

  //find your other control like this
Label Label6=(Label) RepeaterRow.FindControl("controlname")

 //Do here what ever you want
}

或者 您可以使用Rahul singh建议的ItemCommand