public Form1()
{
InitializeComponent();
}
Random g = new Random();
bool b = false;
private void button_click(object sender, EventArgs e)
{
Button button= sender as Button;
b=true;
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += button_click;
button2.Click += button_click;
button3.Click += button_click;
button4.Click += button_click;
button5.Click += button_click;
button6.Click += button_click;
button7.Click += button_click;
button8.Click += button_click;
button9.Click += button_click;
button10.Click += button_click;
button11.Click += button_click;
button12.Click += button_click;
button13.Click += button_click;
button14.Click += button_click;
button15.Click += button_click;
button16.Click += button_click;
button17.Click += button_click;
button18.Click += button_click;
button19.Click += button_click;
button20.Click += button_click;
button21.Click += button_click;
button23.Click += button_click;
button24.Click += button_click;
button25.Click += button_click;
button26.Click += button_click;
StreamReader sr = new StreamReader(@"C:\Users\victus-pc\OneDrive\Desktop\notepad1.txt");
int i;
string s = sr.ReadToEnd();
string[] t = s.Split(',');
int l = g.Next(t.Length);
Label[] l1 = new Label[t[l].Length];
for (i = 0; i < l1.Length; i++)
{
l1[i] = new Label();
l1[i].Size = new Size(30, 30);
l1[i].Left = 20 + 50 * i;
l1[i].Top = 20;
l1[i].Text = t[l][i].ToString();
l1[i].Visible = false;
this.Controls.Add(l1[i]);
}
if (b)
{
for (i = 0; i < l1.Length; i++)
{
if (button.Text.Equals(l1[i].Text))
{
l1[i].Visible = true;
}
else
label2.Text = (int.Parse(label2.Text) - 1).ToString();
break;
}
if (int.Parse(label2.Text) == 0)
MessageBox.Show("Game Over");
b = false;
}
}
I'm a beginner in programming,so please take that into consideration.
I'm trying to create a Hangman game using C# (WindowsForm).
My problem is in if (button.Text.Equals(l1[i].Text))
; it gives me an error that is : "The name "button" does not exist in the current context", though i declared it as name in Button button= sender as Button;
.
Another problem is that in a previous Hangman project, i tried another way but same concept that is to use bool b
like here,and if the user clicked on a button,Form 1
knows that b
becomes true and doesn't stay false.
But that doesn't happen, because Form1
loads before i click on a button,so even if b
becomes true,it cannot load the Form1
again because a form can only be created once ,once we run the program.
So what should i do to fix these 2 problems?