Why does my disableButtons method not work? - c#

I am currently working on a schoolproject for C# and I am making Tic Tac Toe.
I have a little problem though..
My code used to work perfectly fine untill I build in a scoreboard.
I think the scoreboard is overruling the disableButtons.. Before I added the scoreboard it worked perfectly fine..
Can someone look at my code and tell me what's wrong?
It's supposed to work like this:
Play, if there is a winner, disable buttons. Please help me out!
Edit: I don't know why my namespace is in this textfield..
namespace Tic_Tac_Toe
{
public partial class Form1 : Form
{
bool turn = true; //true = x en false = o
int turn_count = 0;
static String player1, player2;
public Form1()
{
InitializeComponent();
}
public static void setPlayerName(String n1, String n2)
{
player1 = n1;
player2 = n2;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Gemaakt door Luca Fraser", "About");
}
private void button_click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (turn)
b.Text = "X";
else
b.Text = "O";
turn = !turn;
b.Enabled = false;
turn_count++;
checkForWinner();
if (turn_count % 2 == 0)
{
lblTurn.Text = player1 + " is aan de beurt";
}
else
{
lblTurn.Text = player2 + " is aan de beurt";
}
}
private void checkForWinner()
{
bool thereIsWinner = false;
//Horizontaal checken
if((btnA1.Text == btnA2.Text) && (btnA2.Text == btnA3.Text) && (!btnA1.Enabled))
thereIsWinner = true;
else if((btnB1.Text == btnB2.Text) && (btnB2.Text == btnB3.Text) && (!btnB1.Enabled))
thereIsWinner = true;
else if((btnC1.Text == btnC2.Text) && (btnC2.Text == btnC3.Text) && (!btnC1.Enabled))
thereIsWinner = true;
//Verticaal checken
if ((btnA1.Text == btnB1.Text) && (btnB1.Text == btnC1.Text) && (!btnA1.Enabled))
thereIsWinner = true;
else if ((btnA2.Text == btnB2.Text) && (btnB2.Text == btnC2.Text) && (!btnA2.Enabled))
thereIsWinner = true;
else if ((btnA3.Text == btnB3.Text) && (btnB3.Text == btnC3.Text) && (!btnA3.Enabled))
thereIsWinner = true;
//Diagonaal checken
if ((btnA1.Text == btnB2.Text) && (btnB2.Text == btnC3.Text) && (!btnA1.Enabled))
thereIsWinner = true;
else if ((btnA3.Text == btnB2.Text) && (btnB2.Text == btnC1.Text) && (!btnC1.Enabled))
thereIsWinner = true;
if (thereIsWinner)
{
disableButtons();
String winner = "";
if (turn)
{
winner = player2;
lblO.Text = (Int32.Parse(lblO.Text) + 1).ToString();
}
else
{
winner = player1;
lblX.Text = (Int32.Parse(lblX.Text) + 1).ToString();
}
MessageBox.Show(winner + " wins!");
}
else
{
if (turn_count == 9)
{
lblDraw.Text = (Int32.Parse(lblDraw.Text) + 1).ToString();
MessageBox.Show("It's a draw!");
}
}
}
private void disableButtons()
{
try
{
foreach (Control c in Controls)
{
Button b = (Button)c;
b.Enabled = false;
}
}
catch { }
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
turn = true;
turn_count = 0;
foreach (Control c in Controls)
{
try
{
Button b = (Button)c;
b.Enabled = true;
b.Text = "";
}
catch { }
}
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 formtwo = new Form2();
formtwo.ShowDialog();
lblXcount.Text = player1;
lblOcount.Text = player2;
lblTurn.Text = player1 + " is aan de beurt";
}
private void mouse_enter(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Enabled)
{
if (turn)
{
b.Text = "X";
}
else
b.Text = "O";
}
}
private void mouse_leave(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Enabled)
{
b.Text = "";
}
}
private void resetWinCountToolStripMenuItem_Click(object sender, EventArgs e)
{
lblO.Text = "0";
lblX.Text = "0";
lblDraw.Text = "0";
}
private void lblOcount_Click(object sender, EventArgs e)
{
}
private void lblOcount_TextChanged(object sender, EventArgs e)
{
}
}
}

Here:
private void disableButtons()
{
try
{
foreach (Control c in Controls)
{
Button b = (Button)c;
b.Enabled = false;
}
}
catch { }
}
When you iterate over a control that is not a Button, you have an exception and the loop ends.
You can try with this:
foreach (Control c in Controls)
{
Button b = c as Button;
if(b != null)
b.Enabled = false;
}

Your existing code tries to parse every control to Button, if it fails and throws exception. You catch it and nothing happens.
Try this code and get only Buttons to disable:
foreach (Button btn in this.Controls.OfType<Button>())
{
btn.Enabled = false;
}
A suggestion: Comment the catch block code while you're developing, because its easy to debug when and where exception occurs.

private void disableButtons()
{
try
{
foreach (Control c in Controls)
{
Button b = c as Button;
if(b != null)
b.Enabled = false;
}
}
catch (Exception e)
{
Console.Writeline(e.ToString());
}
}
You need to check if the control is a button otherwise you will cause an exception to be thrown.
This is a prime example about why it is a BAD idea to swallow exceptions. If you had reported or logged the exception the problem would have been apparent.

Related

I'm getting error Ambiguity between '¨Form1.score' and ¨Form1.score'

i have int score = 0; under public partial class Form1 : Form and Im getting error in txtscore.Text = "Score: " + score; and score = 0; in private void RestartHry() does someone know why is that? Or know how to fix that bsc i have no idea. ......................................................................................................................................................................................
namespace Projekt_Havlík
{
public partial class Form1 : Form
{
bool vpravo, vlevo;
int rychlost = 8;
int score = 0;
int minul = 0;
Random rndX = new Random();
Random rndY = new Random();
PictureBox minulcoin = new PictureBox();
public Form1()
{
InitializeComponent();
RestartHry();
}
private void MainGameTimerEvent(object sender, EventArgs e)
{
//naprogramovaní textboxů
txtscore.Text = "Score: " + score;
txtminul.Text = "Minul: " + minul;
//změnění postavy při jízdě do leva/prava
if (vlevo == true && player.Left > 0)
{
player.Left -= 12;
player.Image = Properties.Resources.main_left;
}
if (vpravo == true && player.Left + player.Width <this.ClientSize.Width)
{
player.Left += 12;
player.Image = Properties.Resources.main_right;
}
}
private void KeyIsUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
vlevo = false;
}
if (e.KeyCode == Keys.Right)
{
vpravo = false;
}
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
vlevo = true;
}
if (e.KeyCode == Keys.Right)
{
vpravo = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void RestartHry()
{
foreach(Control x in this.Controls)
{
if (x is PictureBox &&(string)x.Tag == "coins")
{
x.Top = rndY.Next(80, 300) * -1;
x.Left = rndX.Next(5, this.ClientSize.Width - x.Width);
}
}
player.Left = this.ClientSize.Width / 2;
player.Image = Properties.Resources.main_right;
score = 0;
minul = 0;
rychlost = 8;
vpravo = false;
vlevo = false;
CasovacHry.Start();
}
}
}
Try changing the name of your "score" variable, try calling it like, "myScore", typically if something is ambiguous it is because there are two fields or properties with the same name in assembly references that are not directly specified in the code.

WindowsForms app - keyEvent doesn't work, where is the problem?

I have little problem with my windowsforms app - its a snake game
Everywhing is ok, but after click "Play Again" button app doesn't see any kay Event (I try debug and put break point in KeyIsDown(object sender, KeyEventArgs e); but it isn't call when I clicked Key
Can you tell me where is a problem?
Full repository (little other version, but still doesn't work) : https://github.com/ldidil/snake-game
Short version of the code:
namespace SnakeGame
{
public partial class Form1 : Form
{
private List<Circle> Snake = new List<Circle>();
private Circle food;
public Form1()
{
InitializeComponent();
new Settings();
DisplayTopScore();
gameTimer.Interval = 1000 / Settings.Speed; //TO DO (change speed lvl)
gameTimer.Tick += UpdateScreen;
gameTimer.Start();
StartGame();
}
private void StartGame()
{
GenerateSnake();
GenerateFood();
}
private void UpdateScreen(object sender, EventArgs e)
{
if (Settings.GameOver == false)
{
if (Input.KeyPress(Keys.Right) && Settings.Direction != Directions.Left)
{
Settings.Direction = Directions.Right;
}
else if (Input.KeyPress(Keys.Left) && Settings.Direction != Directions.Right)
{
Settings.Direction = Directions.Left;
}
else if (Input.KeyPress(Keys.Up) && Settings.Direction != Directions.Down)
{
Settings.Direction = Directions.Up;
}
else if (Input.KeyPress(Keys.Down) && Settings.Direction != Directions.Up)
{
Settings.Direction = Directions.Down;
}
MovePlayer();
}
boardCanvas.Invalidate(); //odśwież plansze
}
private void MovePlayer()
{
for (int i = Snake.Count - 1; i >= 0; i--)
{
if (i == 0)
{
switch (Settings.Direction)
{
case Directions.Right:
Snake[i].X++;
break;
case Directions.Left:
Snake[i].X--;
break;
case Directions.Up:
Snake[i].Y--;
break;
case Directions.Down:
Snake[i].Y++;
break;
}
checkCollision(i);
checkFood();
}
else
{
Snake[i].X = Snake[i - 1].X;
Snake[i].Y = Snake[i - 1].Y;
}
}
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
Input.ChangeState(e.KeyCode, true);
}
private void KeyIsUp(object sender, KeyEventArgs e)
{
Input.ChangeState(e.KeyCode, false);
}
private void Die()
{
topScore.Write();
Settings.GameOver = true;
}
private void UpdateGraphic(object sender, PaintEventArgs e)
{
{
if (!Settings.GameOver)
{
draw(e);
}
else
{ //game over
string gameOver = "Game Over\n" + "Final Score: " + Settings.Points;
endText.Text = gameOver;
endText.Visible = true;
playAgainButton.Visible = true;
exitButton.Visible = true;
}
}
}
private void draw(PaintEventArgs e)
{
for (int i = 0; i < Snake.Count; i++)
{
string location;
if (i == 0)
{
location = (#"..\..\Img\snakeHead.png");
}
else
{
location = (#"..\..\Img\snakeBody.png");
}
var img = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + location);
Rotate(img);
Point p1 = new Point(Snake[i].X *Settings.Width, Snake[i].Y * Settings.Height);
e.Graphics.DrawImage(img, p1);
}
Point p2 = new Point(food.X * Settings.Width, food.Y * Settings.Height);
var appleImage = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + #"..\..\Img\apple.png");
e.Graphics.DrawImage(appleImage, p2);
}
private static void Rotate(Bitmap img)
{
switch (Settings.Direction)
{
case Directions.Right:
break;
case Directions.Left:
img.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case Directions.Up:
img.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
case Directions.Down:
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
}
}
private void playAgainButton_Click(object sender, EventArgs e)
{
endText.Visible = false;
playAgainButton.Visible = false;
exitButton.Visible = false;
new Settings(Form2.nickname, Form2.speed);
Snake.Clear();
StartGame();
}
private void exitButton_Click(object sender, EventArgs e)
{
System.Windows.Forms.Application.Exit();
}
}
}
You need to register your KeyIsDown function as event handler for your control - Control.KeyDown Event:
playAgainButton.KeyDown += KeyIsDown;

When players use reset board function on my Tic Tac Toe/ Connect Four game, the game counts every button click as win?

The code works perfectly until the player uses the 'reset board' function the game decides that the any button click afterwards is a winner and the only way to stop this is to close and re-build the application (using visual studio). This is using a WPF application.
I don't know exactly what is causing the issue, but i have a feeling it has something to do with the checkforwinner method and how it checks that all buttons in a row or column by matching all colours. When the board is reset, it changes the colour of all the buttons to color.lightgray which may interfere with the checkforwinner function.
If it is not too much trouble i would also like to add a 'dropping' mechanic like the real connect four and make a more efficient checkforwinner function so i can expand the board to 12 x 8 or so and not have double or triple the amount of checkforwinner if statements, cheers.
Code is below:
public partial class Form1 : Form
{
bool turn = true; //if true it is red turn / if false it is yellow turn
int turn_count = 0; //counts each turn for features such as draw function
bool winner_found = false; // automatically sets winner found function to false to
int win_method;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
win_method = rnd.Next(1, 4);
if (win_method == 1)
{
winMethod.Text = "Horizontal Wins Only";
}
else if (win_method == 2)
{
winMethod.Text = "Vertical Wins Only";
}
else if (win_method == 3)
{
winMethod.Text = "Diagonal Wins Only";
}
}
// function to alternate turns between red and yellow players and count turns for potential draws (see below).
// Also run checkForWinner function after every move (button click)
private void button_click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (turn)
b.BackColor = Color.Yellow;
else
b.BackColor = Color.Red;
turn = !turn;
b.Enabled = false;
turn_count++;
checkForWinner();
}
private void checkForWinner()
{
if (win_method == 1)
//check for horizontal wins
if ((A1.BackColor == A2.BackColor) && (A2.BackColor == A3.BackColor) && (A3.BackColor == A4.BackColor) && (A4.BackColor == A5.BackColor) && (!A1.Enabled))
winner_found = true;
else if ((B1.BackColor == B2.BackColor) && (B2.BackColor == B3.BackColor) && (B3.BackColor == B4.BackColor) && (B4.BackColor == B5.BackColor) && (!B1.Enabled))
winner_found = true;
else if ((C1.BackColor == C2.BackColor) && (C2.BackColor == C3.BackColor) && (C3.BackColor == C4.BackColor) && (C4.BackColor == C5.BackColor) && (!C1.Enabled))
winner_found = true;
else if ((D1.BackColor == D2.BackColor) && (D2.BackColor == D3.BackColor) && (D3.BackColor == D4.BackColor) && (D4.BackColor == D5.BackColor) && (!D1.Enabled))
winner_found = true;
else if ((E1.BackColor == E2.BackColor) && (E2.BackColor == E3.BackColor) && (E3.BackColor == E4.BackColor) && (E4.BackColor == E5.BackColor) && (!E1.Enabled))
winner_found = true;
if (win_method == 2)
//check for vertical wins
if ((A1.BackColor == B1.BackColor) && (B1.BackColor == C1.BackColor) && (C1.BackColor == D1.BackColor) && (D1.BackColor == E1.BackColor) && (!A1.Enabled))
winner_found = true;
else if ((A2.BackColor == B2.BackColor) && (B2.BackColor == C2.BackColor) && (C2.BackColor == D2.BackColor) && (D2.BackColor == E2.BackColor) && (!A2.Enabled))
winner_found = true;
else if ((A3.BackColor == B3.BackColor) && (B3.BackColor == C3.BackColor) && (C3.BackColor == D3.BackColor) && (D3.BackColor == E3.BackColor) && (!A3.Enabled))
winner_found = true;
else if ((A4.BackColor == B4.BackColor) && (B4.BackColor == C4.BackColor) && (C4.BackColor == D4.BackColor) && (D4.BackColor == E4.BackColor) && (!A4.Enabled))
winner_found = true;
else if ((A5.BackColor == B5.BackColor) && (B5.BackColor == C5.BackColor) && (C5.BackColor == D5.BackColor) && (D5.BackColor == E5.BackColor) && (!A5.Enabled))
winner_found = true;
if (win_method == 3)
//check for diagonal wins
if ((A1.BackColor == B2.BackColor) && (B2.BackColor == C3.BackColor) && (C3.BackColor == D4.BackColor) && (D4.BackColor == E5.BackColor) && (!A1.Enabled))
winner_found = true;
else if ((A5.BackColor == B4.BackColor) && (B4.BackColor == C3.BackColor) && (C3.BackColor == D2.BackColor) && (D2.BackColor == E1.BackColor) && (!A5.Enabled))
winner_found = true;
// when winner string is detected to be true than find player who
//won and give players a message box to show this.
// also adds one point to the player who wins the round
if (winner_found)
{
disableButtons();
String winner = "";
if (turn)
{
winner = Color.Red.ToString();
red_win_count.Text = (Int32.Parse(red_win_count.Text) + 1).ToString();
}
else
{
winner = Color.Yellow.ToString();
yellow_win_count.Text = (Int32.Parse(yellow_win_count.Text) + 1).ToString();
}
}
else
{ // if all squares are filled (25 moves) than signal draw as no more moves can be made
if (turn_count == 25)
MessageBox.Show("Draw! Wanna rematch?", "Rematch!");
}
}
// function to disable all buttons for when winner is detected
private void disableButtons()
{
try
{
foreach (Control c in Controls)
{
Button b = (Button)c;
b.Enabled = false;
}
}
catch { }
}
// help -> how to play: instructions on how to play the game in brief terms
private void howToPlayToolStripMenuItem_click(object sender, EventArgs e)
{
MessageBox.Show("Connect Five is quite similar to the good old-fashioned Connect Four, " +
"but there is a lot more spaces for you to play you pieces and you have to connect " +
"five to win! The twist is, that you can only win a certain way, dependent on the " +
"randomly generated direction on the right hand side of the screen. If the direction is " +
"vertical, then you can only win with 5 coloured squares in a vertical line. Same with " +
"horizontal and diagonal directions! Have Fun!", "Connect Five: How To Play");
}
// help -> about: quick about menu of the game, creator and copyright year/ symbol
private void aboutToolStripMenuItem_click(object sender, EventArgs e)
{
MessageBox.Show("Made by Brendan Ellis © 2019", "Connect Five About");
}
// visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
// This and the button_click function clash and i haven't been able to find a fix.
private void fileToolStripMenuItem_click(object sender, EventArgs e)
{
}
// file -> new game: resets complete game board to have a rematch
private void newGameToolStripMenuItem_click(object sender, EventArgs e)
{
turn = true;
turn_count = 0;
Random rnd = new Random();
win_method = rnd.Next(1, 4);
if (win_method == 1)
{
winMethod.Text = "Horizontal Wins Only";
}
else if (win_method == 2)
{
winMethod.Text = "Vertical Wins Only";
}
else if (win_method == 3)
{
winMethod.Text = "Diagonal Wins Only";
}
foreach (Control c in Controls)
{
try
{
Button b = (Button)c;
b.Enabled = true;
b.BackColor = Color.LightGray;
}
catch { }
}
}
// file -> exit game: just exits the game because clicking the cross is obviously sooooo last year
private void exitGameToolStripMenuItem_click(object sender, EventArgs e)
{
Application.Exit();
}
// visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
// This and the button_click function clash and i haven't been able to find a fix.
private void helpToolStrip_click(object sender, EventArgs e)
{
}
private void button_enter(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Enabled)
{
if (turn)
b.BackColor = Color.Yellow;
else
b.BackColor = Color.Red;
}
}
private void button_leave(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Enabled)
{
b.BackColor = Color.LightGray;
}
}
private void resetWinCountersToolStripMenuItem_Click(object sender, EventArgs e)
{
yellow_win_count.Text = "0";
red_win_count.Text = "0";
}
}
Have a play with this code:
public enum WinMethod
{
Horizontal,
Vertical,
Diagonal,
}
public enum Player
{
Yellow,
Red,
}
public partial class Form1 : Form
{
Player turn = Player.Red;
int turn_count = 0; //counts each turn for features such as draw function
bool winner_found = false; // automatically sets winner found function to false to
private WinMethod win_method;
private Dictionary<Player, int> _winnerCount = new Dictionary<Player, int>()
{
{ Player.Yellow, 0 },
{ Player.Red, 0 },
};
public Form1()
{
InitializeComponent();
}
private static Random __rnd = new Random();
private void Form1_Load(object sender, EventArgs e)
{
win_method =
new[] { WinMethod.Horizontal, WinMethod.Vertical, WinMethod.Diagonal }
.OrderBy(_ => __rnd.Next())
.First();
}
// function to alternate turns between red and yellow players and count turns for potential draws (see below).
// Also run checkForWinner function after every move (button click)
private void button_click(object sender, EventArgs e)
{
Button b = (Button)sender;
b.BackColor = turn == Player.Red ? Color.Red : Color.Yellow;
turn = turn == Player.Red ? Player.Yellow : Player.Red;
b.Enabled = false;
turn_count++;
checkForWinner();
}
private void checkForWinner()
{
var grid = new[]
{
new { line = new [] { A1, A2, A3, A4, A5 }, method = WinMethod.Horizontal },
new { line = new [] { B1, B2, B3, B4, B5 }, method = WinMethod.Horizontal },
new { line = new [] { C1, C2, C3, C4, C5 }, method = WinMethod.Horizontal },
new { line = new [] { D1, D2, D3, D4, D5 }, method = WinMethod.Horizontal },
new { line = new [] { E1, E2, E3, E4, E5 }, method = WinMethod.Horizontal },
new { line = new [] { A1, B1, C1, D1, E1 }, method = WinMethod.Vertical },
new { line = new [] { A2, B2, C2, D2, E2 }, method = WinMethod.Vertical },
new { line = new [] { A3, B3, C3, D3, E3 }, method = WinMethod.Vertical },
new { line = new [] { A4, B4, C4, D4, E4 }, method = WinMethod.Vertical },
new { line = new [] { A5, B5, C5, D5, E5 }, method = WinMethod.Vertical },
new { line = new [] { A1, B2, C3, D4, E5 }, method = WinMethod.Diagonal },
new { line = new [] { E1, D2, C3, B4, A5 }, method = WinMethod.Diagonal },
};
winner_found =
grid.Any(g => g.method == win_method && g.line.Select(x => x.BackColor).Distinct().Count() == 1);
if (winner_found)
{
disableButtons();
_winnerCount[turn] += 1;
(turn == Player.Red ? red_win_count : yellow_win_count).Text = _winnerCount[turn].ToString();
}
else
{ // if all squares are filled (25 moves) than signal draw as no more moves can be made
if (turn_count == 25)
MessageBox.Show("Draw! Wanna rematch?", "Rematch!");
}
}
// function to disable all buttons for when winner is detected
private void disableButtons()
{
foreach (Button b in Controls.OfType<Button>())
{
b.Enabled = false;
}
}
// help -> how to play: instructions on how to play the game in brief terms
private void howToPlayToolStripMenuItem_click(object sender, EventArgs e)
{
MessageBox.Show("Connect Five is quite similar to the good old-fashioned Connect Four, " +
"but there is a lot more spaces for you to play you pieces and you have to connect " +
"five to win! The twist is, that you can only win a certain way, dependent on the " +
"randomly generated direction on the right hand side of the screen. If the direction is " +
"vertical, then you can only win with 5 coloured squares in a vertical line. Same with " +
"horizontal and diagonal directions! Have Fun!", "Connect Five: How To Play");
}
// help -> about: quick about menu of the game, creator and copyright year/ symbol
private void aboutToolStripMenuItem_click(object sender, EventArgs e)
{
MessageBox.Show("Made by Brendan Ellis © 2019", "Connect Five About");
}
// visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
// This and the button_click function clash and i haven't been able to find a fix.
private void fileToolStripMenuItem_click(object sender, EventArgs e)
{
}
// file -> new game: resets complete game board to have a rematch
private void newGameToolStripMenuItem_click(object sender, EventArgs e)
{
turn = Player.Red;
turn_count = 0;
win_method =
new[] { WinMethod.Horizontal, WinMethod.Vertical, WinMethod.Diagonal }
.OrderBy(_ => __rnd.Next())
.First();
foreach (Button b in Controls.OfType<Button>())
{
b.Enabled = true;
b.BackColor = Color.LightGray;
}
}
// file -> exit game: just exits the game because clicking the cross is obviously sooooo last year
private void exitGameToolStripMenuItem_click(object sender, EventArgs e)
{
Application.Exit();
}
// visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
// This and the button_click function clash and i haven't been able to find a fix.
private void helpToolStrip_click(object sender, EventArgs e)
{
}
private void button_enter(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Enabled)
{
b.BackColor = turn == Player.Yellow ? Color.Yellow : Color.Red;
}
}
private void button_leave(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Enabled)
{
b.BackColor = Color.LightGray;
}
}
private void resetWinCountersToolStripMenuItem_Click(object sender, EventArgs e)
{
yellow_win_count.Text = "0";
red_win_count.Text = "0";
}
}
It will definitively set winner_found so you should have the same problem as your existing code.

Previous button not working for DataGridView C#

How can I fix the previous button to move backward in dataGridView row?
The next button is working.
It does nothing.
I don't know how to fix that. Any ideas? I would appreciate it.
Here is my code:
int nRow;
private void Form1_Load
{
nRow = DataGridView2.CurrentCell.RowIndex;
}
private void PreviousData_Click
{
if (row>=0)
{
if (row!=0)
{
DataGridView2.Rows[row].Selected = false;
DataGridView2.Rows[--row].Selected = true;
}
else
{
MessageBox.Show("Need More Data!");
}
}
}
int row;
private void DataGridView2_CellClick
{
if (DataGridView2.SelectedRows.Count != -1)
{
row = DataGridView2.CurrentRow.Index;
}
}
Bind the following two events to your previous and next buttons, respectively and it will do the job.
private void PreviousData_Click(object sender, EventArgs e)
{
var currentRow = DataGridView2.CurrentCell.RowIndex;
if (currentRow == 0)
return;
else
currentRow--;
DataGridView2.ClearSelection();
DataGridView2.CurrentCell = DataGridView2.Rows[currentRow].Cells[0];
DataGridView2.Rows[currentRow].Selected = true;
}
private void NextData_Click(object sender, EventArgs e)
{
var currentRow = DataGridView2.CurrentCell.RowIndex;
if (currentRow == DataGridView2.RowCount - 1)
return;
else
currentRow++;
DataGridView2.ClearSelection();
DataGridView2.CurrentCell = DataGridView2.Rows[currentRow].Cells[0];
DataGridView2.Rows[currentRow].Selected = true;
}

2 Dynamic Buttons, 1 Event Handler. How to determine who clicked the event?

I'm trying to determine from my 2 dynamic buttons who click the event handler.
How i create my 2 dynamic buttons at Form load
private void Form1_Load(object sender, EventArgs e)
{
for (int q = 0; q < 2; q++)
{
Point newLoc = new Point(a, b);
for (int i = 0; i <= 3 - 1; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(95, 80);
buttonArray[i].Name = "btn" + q;
buttonArray[i].Text = "btn" + q;
buttonArray[i].Click += newButton;
buttonArray[i].Location = newLoc;
a = a + 10;
if (a > 300)
{
b = b + 100;
a = 1;
}
this.Controls.Add(buttonArray[i]);
}
}
}
The Event I'm trying to call
void newButton(object sender, EventArgs e)
{
if (sender == "btn1")
{
MessageBox.Show("btn1");
}
if (sender == "btn2")
{
MessageBox.Show("btn2");
}
}
It can call the event handler if I do not add the IF statement.
You need to cast the object sender to a Buttonand then test against the Name property:
void newButton(object sender, EventArgs e)
{
Button btn = sender as Button;
// btn could be null if the event handler would be
// also triggered by other controls e.g. a label
if(btn != null)
{
if (btn.Name == "btn1")
{
MessageBox.Show("btn1");
}
if (btn.Name == "btn2")
{
MessageBox.Show("btn2");
}
}
}
In C# 7.0 you can simplify that call:
void newButton(object sender, EventArgs e)
{
if(sender is Button btn)
{
if (btn.Name == "btn1")
{
MessageBox.Show("btn1");
}
if (btn.Name == "btn2")
{
MessageBox.Show("btn2");
}
}
}
You have 2 problems.
One :
buttonArray[i].Name = "btn" + q;
buttonArray[i].Text = "btn" + q;
You should create and pass new value for each button :
int temp = q;
buttonArray[i].Name = "btn" + temp;
buttonArray[i].Text = "btn" + temp;
More details
Two :
if (sender == "btn1")
{
MessageBox.Show("btn1");
}
You're comparing a Button object to a string. What you want to do is to check if your sender is Button at first and then check it's Name property.
Button btn = sender as Button;
if(btn != null)
{
if (btn.Name == "btn1")
{
MessageBox.Show("btn1");
}
}

Categories

Resources