0

Hi all,

I am new to C# and the visual studio express environment.
I have a button on this web page, when it is clicked a method assigns a
new random number to a variable but I want new clicks to add numbers
to what was in the variable and not an overwrite.

Please does anyone have any idea how to make the adding happen without an
re assignment.

Would be very grateful.

Thank you

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by firstimer
0

You can persist values in a cookie, in session, or in viewstate. Here is a demo showing how to do this by using viewstate.

viewstatedemo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="viewstatedemo.aspx.cs" Inherits="viewstatedemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        The running sum total is <asp:Literal ID="litRandomRunningSum" runat="server" />.
        <br /><br />
        <asp:Button ID="btnUpdate" Text="Update Total" runat="server" OnClick="btnUpdate_Click" />
    </div>
    </form>
</body>
</html>

viewstatedemo.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class viewstatedemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            Random random = new Random();
            int initialValue = random.Next(1, 100);
            this.ViewState["total"] = initialValue;
            litRandomRunningSum.Text = initialValue.ToString();
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        int currentTotal = (int)this.ViewState["total"];
        Random random = new Random();
        currentTotal += random.Next(1, 100);
        litRandomRunningSum.Text = currentTotal.ToString();
        this.ViewState["total"] = currentTotal;
    }
}
0

@apegram,

Thank you very much. Your code gave me an idea on how to move forward and I have.

Once again, thanks.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.