Simple OOP mistake

travisowens

Centurion
Joined
Feb 11, 2004
Messages
108
Location
Rochester, NY
Why won't this int keep incrementing?

I just created a simple web page in VS2005 and dropped a button and a label. I simply want the label to increment every time the button is pushed, which works fine the first click, but after that Count is always 1.

What simple thing am I not seeing?

Code:
public partial class _Default : System.Web.UI.Page 
{
	public int _count = new int();

	public void Page_Load(object sender, EventArgs e)
	{
	}
	public void btnIncrement_Click(object sender, EventArgs e)
	{
		Count = Count + 1;
		lblCount.Text = Count.ToString();
	}

	public int Count
	{
		get 
		{
			return _count;
		}
		set
		{
			_count = value;
		}
	}
}

and if you want to see the generated HTML

Code:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
		<asp:Button ID="btnIncrement" runat="server" OnClick="btnIncrement_Click" Text="Increment" /><br />
		<asp:Label ID="lblCount" runat="server" Text="0"></asp:Label></div>
    </form>
</body>
</html>
 
Last edited:
Since you are storing the value in your own variable, and not using the text of the label you will need to do something like


C#:
	public int Count
	{
		get 
		{
			return Session("m_count");
		}
		set
		{
			Session("m_count") = value;
		}
	}

The reason for this is because everytime you click the button the page reloads, and the value is reset back to 0 and then increased.

Putting the value in a Session Variable will keep the value across page loads, additonally you could use this value in a completely different webpage through: Session("m_count").
 
Thanks!

I wasn't even thinking, my brain is in WinForms mode, I don't know why I had forgotten about using a session.

PS: in any kind of collection/array in C# it's [] not ()
 
Oops, I didn't compile the code, just wrote it in the forum here. Glad you caught it, and knew the difference. Working on a VB project now, so I'm in VB mode...
 
No biggie, I do it too, for awhile I was working on a classic ASP app and when I went back to my C# code, I forgot all my ;s and didn't notice until the build didn't work.
 
Depends what you want to do with that count next, you may also store the value in viewstate instead of session.
 
Back
Top