Jump to content

Beginner C# question, need help

- - - - -

  • Please log in to reply
4 replies to this topic

#1
BrendonA

BrendonA

    Newbie

  • Members
  • Pip
  • 2 posts
Hi,

I have just started learning c# and basically using c# with visual Studio and I need some help. Pardon me if I have posted this in the wrong section.

I have a simple question here:


I have a button name add "10dollars" , a label named balance with text "0",

How do I add another 10 dollars to the balance whenever the add 10dollars button is click?

My logic is :

protected void Button1_Click(object sender, EventArgs e){
int add =10;
int balance = 0;


add = balance + add;
Label3.Text = add.ToString();
}

It'll add 10 to the balance on the first click but not the subsequent clicks, how do i change the codes to make it work?

Hope you understand my question, thanks for your help in advance !

#2
CommittedC0der

CommittedC0der

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,565 posts
What you want is every time you click the add button it adds 10. Your problem is this line here:
add = balance + add;

Every time the button is clicked add is re-assigned the value of balance+add. We want it to add that value each time. To do that we do this:
add [COLOR=#ff0000]+=[/COLOR] balance+add

So now every time its called it adds balance+add to adds original value.

Hope you understand that. :)
~ Committed.
A man can be defined by what he does when no one is looking.
Science is only an educated theory, which we cannot disprove.

#3
Vaielab

Vaielab

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 547 posts
protected int add =10;

protected int balance = 0;


protected void Button1_Click(object sender, EventArgs e){

add = balance + add;

Label3.Text = add.ToString();

}

You need to keep in memory the balance between each click, so you need to keep the declaration outside of the click event

#4
CommittedC0der

CommittedC0der

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,565 posts

Quote

protected int add =10; protected int balance = 0; protected void Button1_Click(object sender, EventArgs e){ add = balance + add; Label3.Text = add.ToString(); } You need to keep in memory the balance between each click, so you need to keep the declaration outside of the click event

Actually your right! I totally miss read that code.
~ Committed.
A man can be defined by what he does when no one is looking.
Science is only an educated theory, which we cannot disprove.

#5
BrendonA

BrendonA

    Newbie

  • Members
  • Pip
  • 2 posts
Thanks for all the replies ! I managed to made it work with another method as well.

int newvalue;
int total;

newvalue = int.Parse(Label1.Text);

total = newvalue + 50;

(Label1.Text) = Convert.ToString(total);




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users