0

I'm building an ASPX web page where some links will be visible or invisible depending on the user's access level. My thought was rather than create multiple functions and turn each link on or off, I could keep things neat and tidy by making List<LinkButton> members, like:

private List<LinkButton> adminButtons = new List<LinkButton>();
private List<LinkButton> guestButtons = new List<LinkButton>();
private List<LinkButton> userButtons = new List<LinkButton>();

Then I'd call one function to make them all visible or invisible.

private void DisplayButtons(List<LinkButton> linkButtons, bool displayButtons) {
            for (int i = 0; i < linkButtons.Count; i++) {
                linkButtons[i].Visible = displayButtons;
            }
        }

But I hit two snags. Firstly, I couldn't figure out how to initialize the lists with the links. For example, I've got asp:LinkButtons with IDs like ID='Link_UserManagement', ID='Link_InventoryManagement', et cetera. I can do this in the ASPX.CS file, and it works:

Link_UserManagement.Visible = false;
Link_InventoryManagement.Visble = true;

But this doesn't work:

private List<LinkButton> adminButtons = new List<LinkButton>() { Link_UserManagement }

And then if I try adding them this way, then the List count increases, but the values are null:

adminButtons.Add(Link_UserManagement);

So obviously I don't understand something about how these links work. My question is, why isn't this working the way I thought it would?

Secondly, if there's a better way to go about hiding and showing content based on a user's access level, I'm open to suggestions.

Ransom
  • 103
  • 1
  • 1
  • 4
  • This is probably a matter of timing and lifecycle. `Link_UserManagement` is not initialized when your object is first constructed, for example, so its reference will be `null` when it's referenced in the constructor. Try moving your `adminButtons.Add(...)` to a later event method, like `Load`. See https://learn.microsoft.com/en-us/previous-versions/aspnet/ms178472(v=vs.100) – StriplingWarrior Jan 13 '21 at 22:53
  • 1
    Well on top on what @StriplingWarrior said also you cant save the adminButtons on viewstate or session. So after each load you will have those variable reset. ASP.net life circle is very imported to understand. You will need to save an index or IDs in viewstate instead and retrieve those linkbuttons by manually loop in the container of those buttons – Alen.Toma Jan 13 '21 at 23:13

0 Answers0