Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Setting an int from inside a method

Paul CarsonPaul Carson Member Posts: 1

Hi I'm trying to reset item1 to a new variable after I click the random newDayButton. At the moment it sets the text correctly but when I try to solve using the AnswerButton, the int is still set to 0?

`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp3
public partial class Form1 : Form
int item1 = 0;
int item2 = 10;

    public Form1()
        Number1.Text = "" + item1;
        Number2.Text = "" + item2;

    private void newDayButton_Click(object sender, EventArgs e)
        Random rnd = new Random();
        int item1 = rnd.Next(1,10);
        Number1.Text = "" + item1;


    private void AnswerButton_Click(object sender, EventArgs e)
        Sums test = new Sums();

        int result = test.multiplynumbers(item1, item2);
        answerText.Text = result.ToString();          




  • Phill CahillPhill Cahill Member Posts: 1

    The item1 declared in newDayButton is only available within the scope it was defined and is separate to the global variable item1 defined in the class. Because the item one in newDayButton is not available to the AnswerButton method the global item1 is used which has never been changed from 0.

    I think if you remove the int decleration from your newDayButton to read item1 = rnd.Next(1,10); you will be closer to achieving what I think your trying to achieve.

Sign In or Register to comment.