I am working on a dice roller program, we are suppose to have a "Total Money Earned" label box which shows the total amount of money earned when the roller rolls the dice. if you roll a 6 you earn 600 dollars if you earn a 5 you earn 500 dollars etc etc. I can get the dollar value to show up on the label box but when i continue rolling, the number will be replaced by the next value instead of summing to for example roll a 5 then you earn 500 dollar then hit roll again you roll 1 and then it should show $600 = 500 + 100.
Please help heres the code im using
private void button1_Click(object sender, EventArgs e)
{
int roll1;
Random rand = new Random();
roll1 = rand.Next(6) + 1;
int value = 100;
int sum = (roll1 * value);
totalmoneyLabel.Text = sum.ToString("c");
if (roll1 == 1)
{
diceBox1.Image = drios1_Project2.Properties.Resources._1Die;
}
if (roll1 == 2)
{
diceBox1.Image = drios1_Project2.Properties.Resources._2Die;
}
if (roll1 == 3)
{
diceBox1.Image = drios1_Project2.Properties.Resources._3Die;
}
if (roll1 == 4)
{
diceBox1.Image = drios1_Project2.Properties.Resources._4Die;
}
if (roll1 == 5)
{
diceBox1.Image = drios1_Project2.Properties.Resources._5Die;
}
if (roll1 == 6)
{
diceBox1.Image = drios1_Project2.Properties.Resources._6Die;
}
}
You need to create a running total and add that to your label, It will need to be a class level variable that way you are not initializing it during each roll something like this should work. You can then reset it back to zero when you are finished.
public partial class Form1 : Form
{
int roll1;
int runningTotal;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Random rand = new Random();
roll1 = rand.Next(6) + 1;
int value = 100;
int sum = (roll1 * value);
runningTotal += sum;
label1.Text = runningTotal.ToString("c");
}
}
It is not written anywhere what is your application. Is it forms application, ASP.Net application or something else. In any cases, you must get previous value and add new value to it.
To do this in ASP.Net application, you can get value from label or from hiddenfield where you contains only value without $ sign. To get value from label use code:
int previousValue;
if (!int.TryParse(totalMoneyLabel.Text, out previousValue))
previousValue = 0;
Full example:
private void button1_Click(object sender, EventArgs e)
{
const int value = 100;
int previousValue;
if (!int.TryParse(totalMoneyLabel.Value, NumberStyles.Integer, new CultureInfo("en-Us"), out previousValue))
previousValue = 0;
var rand = new Random();
var roll1 = rand.Next(6) + 1;
var sum = previousValue+(roll1 * value);
totalMoneyLabel.Text = sum.ToString("c", new CultureInfo("en-Us"));
....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With