简体   繁体   中英

Access linkbutton from datalist on pageload with c# asp.net

I have this linkbutton within a datalist and I'm trying to get access to the datalist on the pageload so i can set the linkbutton to be enabled or not based on the user's role.

<asp:DataList id="dlRecommendations" runat="server" DataKeyField="Key" Width="900">
   <ItemTemplate>
      <asp:LinkButton id="lnkEdit" Text="Edit" Runat="server" CommandName="Edit">    
      </asp:LinkButton>
  </ItemTemplate>
</asp:DataList>

Within the page load I want to be able to access the linkbutton to enable or disable it based on the user's role.

 private void Page_Load(object sender, System.EventArgs e) {
  //perhaps something like this:
  lnkEdit.Enabled = false;
  ....
}

I think you will be populating the datalist the first time page is loaded. So just wireup ItemDataBound, find link and disable it.

    void dlRecommendations_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        var link = e.Item.FindControl("lnkEdit") as LinkButton;
        if (link != null)
        {
            link.Enabled = UserHasRight;//if user has right then enabled else disabled
        }
    }

DataList is a databound control - it builds rows only when data is supplied. To access link inside row use ItemDataBound event and access e.Item.FindControl("linkId");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM