locked
Session is only available after second click! RRS feed

  • Question

  • User-409252984 posted

    Hi!

    I have a generic list that that is saved into session on Click event. And a Page_Load method on the MasterPage that populates a Label from that list. The only problem is the label gets populated when I click the button the second time, on the third click it looks lik the button was clicked only twice.

    This my Master Page:

    <body style="margin:0px; padding: 0px; font-family: Verdana; text-align: center">
        <form id="BodyForm" runat="server">
            <asp:Panel ID="ListPanel" runat="server"></asp:Panel>
        </form>
    </body>
    

    This is my code behind master:

    private void Page_Load(object sender, EventArgs e)
    {
        List<Label> LabelList = new List<Label>();
        KosaricaList = (List<Label>)(Session["LabelList"]);
        if (LabelList == null)
        {
            Label EmptyLabel = new Label();
            EmptyLabel.Text = "There is nothing on the list";
            ListPanel.Controls.Add(EmptyLabel);
        }
        else
        {
            foreach (Label nameLabel in LabelList)
            {
                Label NameLabel = new Label();
                NameLabel.Text = nameLabel.Text;
                ListPanel.Controls.Add(NameLabel);
            }
        }
    }
    
    



    This is my Default page:

    <asp:Label ID="Label1" runat="server" Text="Name1"></asp:Label>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <asp:Label ID="Label2" runat="server" Text="Name2"></asp:Label>
    <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
    <asp:Label ID="Label3" runat="server" Text="Name3"></asp:Label>
    <asp:Button ID="Button3" runat="server" Text="Button" OnClick="Button3_Click" />
    

    And this is my code behind for the button_click event. Every button raises the same event, this example is for Button1:

    List<Label> LabelList = new List<Label>();
    LabelList = (List<Label>)(Session["LabelList"]);
    if (LabelList == null)
    {
    LabelList = new List<Label>();
    LabelList.Add(Label1);
    Session["LabelList"] = LabelList;
    }
    else
    {
    LabelList.Add(Label1);
    Session["LabelList"] = LabelList;
    }
    

    So the result looks like this

    Before the click: There is nothing on the list

    1st click: There is nothing on the list

    2nd click: Name1

    3rd click: Name2

    I Apreciate every help.

    Thanx

    Sunday, August 26, 2012 1:35 PM

Answers

  • User1779161005 posted

    I've not done web forms for some years now, so forgive me if my memory is hazy, but I am guessing that you have an event ordering problem. Page_Load fires before button click events. Put break points in all of these events and see if that's the issue.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, August 26, 2012 1:51 PM