I've got 2 functions each for specific button, which on of them finds random number and I want second function to only use that number without generating it again. I've tried to do in many ways, now my code is a little experimental but I didn't find a proper way to do it.
public partial class Form1 : Form
{
public int ShuffleNor(int l)
{
int r = 0;
string[] nor = File.ReadAllLines(@"C:\Users\Kapi\Desktop\no.txt").ToArray();
Random rnd = new Random();
r = rnd.Next(0, nor.Length);
lbl_nor.Text = nor[r];
return r;
}
public Form1()
{
InitializeComponent();
}
private void btn_shuffle_Click(object sender, EventArgs e)
{
ShuffleNor(1);
}
private void btn_check_Click(object sender, EventArgs e)
{
string[] eng = File.ReadAllLines(@"C:\Users\Kapi\Desktop\en.txt").ToArray();
lbl_eng.Text = eng[ShuffleNor(0)];
}
}
CodePudding user response:
the answer of tia is correct:
public partial class Form1 : Form
{
public int ShuffleNor(int l)
{
int r = 0;
string[] nor = File.ReadAllLines(@"C:\Users\Kapi\Desktop\no.txt").ToArray();
Random rnd = new Random();
r = rnd.Next(0, nor.Length);
lbl_nor.Text = nor[r];
return r;
}
public Form1()
{
InitializeComponent();
}
int _lastShuffleResult = 0;
private void btn_shuffle_Click(object sender, EventArgs e)
{
_lastShuffleResult = ShuffleNor(1);
}
private void btn_check_Click(object sender, EventArgs e)
{
string[] eng = File.ReadAllLines(@"C:\Users\Kapi\Desktop\en.txt").ToArray();
lbl_eng.Text = eng[_lastShuffleResult];
}
}
CodePudding user response:
Declare a variable at class scope:
public partial class Form1 : Form
{
private int r;
public int ShuffleNor(int l)
{
r = 0;
[...]
If you make it public it will be visible to code that references instances of the class object. If you make it static, the same value/storage is used by all instances of the class.