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

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


<%@ 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">
    <form id="form1" runat="server">
        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" />


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;


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

Once again, thanks.