如何在asp.net中动态设置控件的ID

时间:2018-10-28 17:28:44

标签: asp.net

如何使用Eval方法将id设置为动态,并将sql数据库中的id设置为控制器,就像这样

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="articlesqlfetch">
      <ItemTemplate>
           <strong > <%# Eval("title") %>  </strong> 
               <br>
<-! this is the line   ->
           <asp:HyperLink ID="_<%# Eval("id") %>" runat="server">قراءة المزيد</asp:HyperLink>         
      </ItemTemplate>   

这样做时会给我一个解析器错误

1 个答案:

答案 0 :(得分:1)

不允许使用Eval()提供动态生成的ID,因为您无法绑定到服务器控件的ID属性,因此此代码是错误的:

<asp:HyperLink ID="_<%# Eval("id") %>" runat="server">some text</asp:HyperLink>

相反,将ItemDatabound事件用于转发器控制是这样的(假设您的ID是自动生成的身份字段):

标记(ASPX)

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="articlesqlfetch" 
              OnItemDataBound="Repeater1_ItemDataBound">
    <ItemTemplate>
        <%-- repeater contents --%>
        <asp:HyperLink ID="Hyperlink1" runat="server">some text</asp:HyperLink>
    </ItemTemplate>
</asp:Repeater>

隐藏代码

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    HyperLink hyperlink = e.Item.FindControl("Hyperlink1") as HyperLink;
    if (hyperlink != null) 
    {
        hyperlink.ID = "_" + (e.Item.ItemIndex + 1).ToString(); // set ID from bound data
        hyperlink.ClientIDMode = ClientIDMode.Static;
        hyperlink.NavigateUrl = "some/uri/here"; // optional

        // other stuff
    }
}