0

Hi Stackoverflow community! I'm working on a Sharepoint 2013 Server with Visual Studio 2012 and Windows Server 2012. So, I have to build a Webpart which should add a link via textbox to the GUI. Furthermore, it should be possible to add another link as well. After adding a new link, the whole collection of links should be displayed in a list. The problem is now: after adding a link, the site reloads. As a consequence the array, which stores the links, does only contain the latest link. All previous links are gone/deleted.

Here's my approach on this:

    protected void Page_Load(object sender, EventArgs e) {
        if (Page.IsPostBack) {
            Events = new List<String>();
        }
    }

    protected void btnAddLink_click(object sender, EventArgs e) {
        AddToList();
        List<String> links = Events;
        foreach (String s in links) {
            HyperLink link = new HyperLink();
            link.NavigateUrl = s;
            link.Text = s;
            lnkPanel.Controls.Add(link);
        }
        foreach (String l in links) {
            tbDescription.Text += l + "\n";
        } 
    }

    public List<String> Events {
        get { return (List<String>)ViewState["HyperLinkList"]; }
        set { ViewState["HyperLinkList"] = value; }
    }

    public void AddToList() {
        List<String> events = Events; // Get it out of the viewstate
        String l = tbLinks.Text; // tb = textbox (user input)
        HyperLink link = new HyperLink();
        link.NavigateUrl = tbLinks.Text;
        link.Text = tbLinks.Text;
        if (!events.Contains(link.NavigateUrl.ToString())) {
            events.Add(l);
        }
        Events = events; // Add the updated list back into the viewstate

    }

I hope someone can help me with my (maybe nooby) problem.

Jürgen Stürmer
  • 175
  • 1
  • 2
  • 11

1 Answers1

2

Ahhh you need this:

protected void Page_Load(object sender, EventArgs e) {
    if (!Page.IsPostBack) {
        Events = new List<String>();
    }
}

Each time the page is loaded, your wiping the contents of the list in viewstate. You need to add the ! to make sure it's not a postback.

Jason Evans
  • 28,042
  • 13
  • 88
  • 145