C# - How to access property of an array object? - c#

I dont know how to show clearly, so:
Example - I create an array of button like this:
Button[,] _button = new Button[3, 3];
public MainPage()
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
_button[i, j] = new Button();
_button[i, j].Name = "btn" + i.ToString() + j.ToString();
_button[i, j].Tag = 0;
//Add Click event Handler for each created button
_button[i, j].Click += _button_Click;
boardGrid.Children.Add(_button[i, j]);
Grid.SetRow(_button[i, j], i);
Grid.SetColumn(_button[i, j], j);
}
} // end MainPage()
private void _button_Click(object sender, RoutedEventArgs e)
{
Button b = (Button)sender;
if (...)
b.Tag = 1;
else
b.Tag = 2;
}// end Click Event
Now how can I compare the Tag of 2 buttons in that array like:
b[1,1].Tag == b[1,2].Tag ? ...<do st>... : ....<do st>...

If you need to find position of control in array consider to set Control.Tag to that position instead of search:
_button[i, j].Tag = new System.Drawing.Point{ X = j, Y = i};
And instead of searching just
Point position = (Point)((Button)sender).Tag;
Or if you need more information (like Position + 0/x/empty choice you have) - have custom class to hold all information you need:
enum CellState { Empty, Player1, Player2 };
class TicTacToeCell
{
public Point Position {get;set;}
public CellState State {get;set;}
}
Now when you have position and state - use _buttons array to index access other ones:
Check same row:
Point position = (Point)((Button)sender).Tag;
int player1CountInThisRow = 0;
for (var col = 0; col < 3; col++)
{
if (((TicTacToeCell)(_button[position.Y, col].Tag).State == CellState.Player1)
{
player1CountInThisRow ++;
}
}

This is more of a long-winded clarification than a definite answer, but it may uncover what you're really trying to do:
In the code that you show b is (presumably) a single Button, not an array of buttons. Do you mean:
_button[1,1].Tag == _button[1,2].Tag ? ...<do st>... : ....<do st>...
Or are you trying to compare b (the event sender) to a button relative to it in the array?

Related

Getting Button location in array by clicking on it

I have a grid made out of modified buttons named in the code as GridEl. Every GridEl are inside the array named as Grid[,], i want to get GridEl's location in array by clicking on it, how i can do it?
For example it have to write in the console the row and the column, and that's how it should look in the console: "Row: 2; Column: 5". Of course every button have to write its own location.*
void CreateGrid()
{
GridEl[,] Grid = new GridEl[4, 6];
int c, r, gcount; // c = Column, r = Row, gcount = GridEls count
c = 0; r = 0; gcount = 0;
while ((c < 7)&&(r < 5) && (gcount != 24)) //Loop that creates grid
{
if ((c == 6) && (r < 4))
{
r++;
c = 0;
}
Grid[r, c] = new GridEl();
Grid[r, c].Size = new System.Drawing.Size(64, 64);
Grid[r, c].Location = new System.Drawing.Point(21 * 3 * c, 21 * 3 * r);
MainForm.Controls.Add(Grid[r,c]);
c++;
gcount++;
}
}
public class GridEl : Button
{
//here is the code of GridEl
}
Use this for your GridEl button class definition
public class GridEl : Button
{
public int R { get; set; }
public int C { get; set; }
}
Add this to your while loop
Grid[r, c].R = r;
Grid[r, c].C = c;
Grid[r, c].Click += OnClick;
and finally your Click event handler for the button
private void OnClick(object sender, EventArgs eventArgs)
{
GridEl thisButton = sender as GridEl;
Console.WriteLine($"Row: {thisButton.R}; Column: {thisButton.C}");
}
What you are doing here is simply setting the Row and Column values on the grid button itself, so it always know what the value is and is accessible when it needs it.

Assign different text name in an array button using different function

I have a 2x2 button array and I want to give it a different text name.
Button[,] btnSeat = new Button[2, 2];
private void initializeBoard()
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
btnSeat[i, j] = new Button();
btnSeat[i, j].Width = 90;
btnSeat[i, j].Height = 90;
pnlSeat.Controls.Add(btnSeat[i, j]);
}
}
IT will have an output like this
How can I assign a text using different function
public void assignName()
{
//assign button names
}
Is there anything stopping you from passing the button as a parameter?
public void assignName(Button button)
{
button.Text = "ex";
}
Edit
Since your naming convention is known ahead of time, you can just use a map.
string[,] buttonNames = new string[2,2];
buttonNames[0,0] = "dog";
// continue
Then if you want to use the separate function, you would need to pass in 3 parameters.
public void assignName(Button button, int row, int column)
{
string[,] buttonNames = new string[2,2];
buttonNames[0,0] = "dog";
// continue
buttonText.Text = buttonNames[row][column];
}
Notes
I would either make the name map static at the class level and assigned in a static constructor or dispense with the function, declare the name map in the initializeBoard method and just use it in there.
For example
private void initializeBoard()
{
string[,] buttonNames = new string[2,2];
buttonNames[0,0] = "dog";
// continue
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
btnSeat[i, j] = new Button();
btnSeat[i, j].Width = 90;
btnSeat[i, j].Height = 90;
btnSeat[i, j].Text = buttonNames[row][column];
pnlSeat.Controls.Add(btnSeat[i, j]);
}
}
}
Does that help?

Random labels in Tic Tac Toe simulation

I am working on a Tic Tac Toe simulator for a class and have run into an issue.
I created a 2-dimensional array to simulate the board and populate it with either 0 or 1 in all the boxes.
The issue I am having is getting those numbers to apply to the labels I have created (a1, a2, a3, b1, b2, etcetera).
Is there a way that my nested for loops can have each element in the array apply to a new label? I can't seem to find anything in my book or online about this.
Here is my related code:
private void newBTN_Click(object sender, EventArgs e)
{
Random rand = new Random();
const int ROWS = 3;
const int COLS = 3;
int [,] board = new int[ROWS, COLS];
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLS; col++)
{
board[row, col] = rand.Next(1);
}
}
}
What are the names of the labels? I assumed below that the labels are Label0_0, Label0_1, Label1_1 and so on... This way you can find them using the row and column values.
You want to find the Label control on your form dynamically, because you don't know the name in advance while coding.
If you know the name in advance you just say: label1.Text = "1";.
But in your case, you are trying to find a particular control in each iteration of the loop. So you need to have a name for the labels so you can find them using Form.Controls.Find(string, bool) like this:
var row = 4;
var col = 6;
var l = this.Controls.Find("Label" + row.ToString() + "_" + col.ToString(), false).FirstOrDefault() as Label;
if (l == null)
{
//problem... create label?
l = new Label() { Text = "X or O" }; //the position of this need to be set (the default is 0,0)
this.Controls.Add(l);
}
else
{
l.Text = "X or O";
}
Your board stores integers, which is an internal representation of your game state. You can create a UniformGrid that holds Label for your game GUI. The code below returns a grid based on your current board. You need to add this returned grid to your MainWindow (or whatever you use) to see it.
private UniformGrid fillLabels(int[,] board)
{
int numRow = board.GetLength(0);
int numCol = board.GetLength(1);
UniformGrid g = new UniformGrid() { Rows = numRow, Columns = numCol };
for (int i = 0; i < numRow; i++)
{
for (int j = 0; j < numCol; j++)
{
Label l = new Label();
l.Content = (board[i, j] == 0) ? "O" : "X";
Grid.SetRow(l, i);
Grid.SetColumn(l, j);
g.Children.Add(l);
}
}
return g;
}
First, do not re-create (and re-initialize) Random each time you need it: it makes generated sequences skewed badly:
private static Random s_Rand = new Random();
Try not implement algorithm in the button enent directly, it's a bad practice:
private void CreateField() { ... }
private void newBTN_Click(object sender, EventArgs e) {
CreateField();
}
putting all together:
private static Random s_Rand = new Random();
private void ApplyLabelText(String name, String text, Control parent = null) {
if (null == parent)
parent = this;
Label lb = parent as Label;
if ((lb != null) && (String.Equals(name, lb.Name))) {
lb.Text = text;
return;
}
foreach(Control ctrl in parent.Controls)
ApplyLabelText(name, text, ctrl);
}
private void CreateField() {
for (Char row = 'a'; row <= 'c'; ++row)
for (int col = 1; col <= 3; ++col)
ApplyLabelText(row.ToString() + col.ToString(), s_Rand.Next(1) == 0 ? "O" : "X");
}
private void newBTN_Click(object sender, EventArgs e) {
CreateField();
}
How about you skip the INTEGER board and go directly to a Label array?
You can then do the following to loop trough all of them:
Label[,] listOfLabels; // Do also initialize this.
foreach(Label current in listOfLabels)
{
current.Text = _rand.Next(2) == 0 ? "0" : "X";
}

c#: Creating a 10x10 field (and array) of CheckBoxes

I have a problem, and i don't know why but i can't figure out what it actually is.
All I want to do is create a 10 x 10 field of checkboxes as a board for a game basically.
The thing I came up with should use an Array of these boxes to easily identify them from box[0,0] to box[9,9] according to theirt coordinates in the field.
This is the code i am struggling with:
private void Form1_Load(object sender, EventArgs e)
{
// == OPTIONS ========================================
int xpos = 60; // Position of the first Checkbox (x)
int ypos = 60; // Position of the first Checkbox (y)
int size = 10; // Number of Rows and Columns
int spc = 30; // Space between boxes (Default:20)
// ====================================================
//other Variables
int x, y;
//Creating the Game Field
CheckBox[,] box = new CheckBox[size,size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
box[i, j] = new CheckBox();
//For Debugging Purpuses: Showing i and j next to checkBox
box[i, j].Text = i + "" + j;
//Set Position
y = i * spc + xpos;
x = j * spc + ypos;
box[i, j].Location = new Point(x,y);
this.Controls.Add(box[i, j]);
}
}
}
All I get from this is one single column of checkboxes marked [0,0] to [0,9].
And even if i switch around x and y or i and j, that never changes. So i.E. i will never get a row of checkboxes, just always a single column. Where am I going wrong with this?
i just get those 10 checkboxes, nothing more. they do not seem to be placed over each other either.
Hope you can help me out here :) thanks.
timo.
The check-boxes are too wide by default.
Try it with (for example):
int spc = 50;
And also add this in the loop:
box[i, j].Width = 40;

C# label control not working properly

When I run the following code, it populates the label1 control one time. Then the label1 control does nothing else. How do I get the label1 control to change on the mouse enter events. Please provide code examples.
int currentXposition, currentYposition;
const string positionLabel = "Current Position: ";
private void Test_Load(object sender, EventArgs a)
{
var temp=Color.Transparent; //Used to store the old color name of the panels before mouse events
var colorName = Color.Red; //Color used to highlight panel when mouse over
int numBlocks = 8; //Used to hold the number of blocks per row
int blockSize=70;
//Initialize new array of Panels new
string[,] Position = new string[8, 8];
Panel[,] chessBoardPanels = new Panel[numBlocks, numBlocks];
string Alphabet = "A,B,C,D,E,F,G,H";
string Numbers ="1,2,3,4,5,6,7,8";
string[] alphaStrings = Alphabet.Split(',');
string[] numStrings=Numbers.Split(',');
// b = sub[0];
int FirstValue, SecondValue;
//Store Position Values
for (int firstValue = 0; firstValue < 8; ++firstValue)
{
FirstValue = Alphabet[firstValue];
for (int SecValue = 0; SecValue < 8; ++SecValue)
{
SecondValue = Numbers[SecValue];
Position[firstValue, SecValue] = alphaStrings[firstValue] + numStrings[SecValue];
}
}
//Loop to create panels
for (int iRow = 0; iRow < numBlocks; iRow++)
{
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
Panel p = new Panel();
//set size
p.Size = new Size(blockSize, blockSize);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(blockSize *iRow+15, blockSize * iColumn+15);
chessBoardPanels[iRow, iColumn] = p;
chessBoardPanels[iRow,iColumn].MouseEnter += (s,e) =>
{
currentXposition = iRow;
currentYposition = iColumn;
var oldColor = (s as Panel).BackColor;
(s as Panel).BackColor = colorName;
temp = oldColor;
label1.Text = Position[iRow, iColumn];
};
chessBoardPanels[iRow, iColumn].MouseLeave += (s, e) => {
(s as Panel).BackColor = temp;
};
groupBox1.Controls.Add(p);
}
}
}
I'm answering this only because I think it's important to show what happens when scope is confused. The reason you're having your issue is the scope of your variables. Your label is changing iRow * iColumn times, but only during initial execution. From then on, iRow and iColumn are fixed at their final values.
To achieve your desired end goal, it'd be easiest to create an extension of Panel:
public class ChessPanel : Panel {
private const Color HighlightColor = Color.Red;
public int iColumn { get; set; }
public int iRow { get; set; }
public Color PrimaryColor { get; set; }
public ChessPanel() : base()
{
this.MouseEnter += (s,e) =>
{
this.PrimaryColor = this.BackColor;
this.BackColor = HighlightColor;
};
this.MouseLeave += (s,e) =>
{
this.BackColor = this.PrimaryColor;
};
}
}
This will then allow you to reduce your code as follows:
int currentXposition, currentYposition;
const string positionLabel = "Current Position: ";
private void Test_Load(object sender, EventArgs a)
{
var temp=Color.Transparent; //Used to store the old color name of the panels before mouse events
var colorName = Color.Red; //Color used to highlight panel when mouse over
int numBlocks = 8; //Used to hold the number of blocks per row
int blockSize=70;
//Initialize new array of Panels new
string[,] Position = new string[8, 8];
ChessPanel[,] chessBoardPanels = new ChessPanel[numBlocks, numBlocks];
string Alphabet = "A,B,C,D,E,F,G,H";
string Numbers ="1,2,3,4,5,6,7,8";
string[] alphaStrings = Alphabet.Split(',');
string[] numStrings=Numbers.Split(',');
int FirstValue, SecondValue;
//Store Position Values --- no idea what this is supposed to do...
for (int firstValue = 0; firstValue < 8; ++firstValue)
{
FirstValue = Alphabet[firstValue];
for (int SecValue = 0; SecValue < 8; ++SecValue)
{
SecondValue = Numbers[SecValue];
Position[firstValue, SecValue] = alphaStrings[firstValue] + numStrings[SecValue];
}
}
//Loop to create panels
for (int iRow = 0; iRow < numBlocks; iRow++)
{
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
ChessPanel p = new ChessPanel();
//set size
p.Size = new Size(blockSize, blockSize);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(blockSize *iRow+15, blockSize * iColumn+15);
p.MouseEnter += (s,e) =>
{
var cpSelf = s as ChessPanel;
if (cpSelf != null)
{
label1.Text = Position[cpSelf.iRow, cpSelf.iColumn];
}
};
groupBox1.Controls.Add(p);
chessBoardPanels[iRow, iColumn] = p;
}
}
}
I'm assuming you're making use of many of those variables later on int the program, and looking at this kind of makes my head hurt, so I left most of it in place.
Delegates are a very powerful and useful utility, but they can cause confusion with variable scope. Be very careful when using these, and make sure you treat them as functional units that execute later and can therefore only rely on the state of the program at execution of the block rather than at creation of the block. If you notice, I kept the reference to the Position array simply to show that you can still access local variables within the scope of the delegate because it is technically still in scope. Structurally, this could easily be moved into the ChessPanel class and referenced 100% locally. This example should be used as a caution as it can show how a "local" variable that many people assume are garbage-collected at end of function execution can hang around and eat up memory.
This code is untested and may have minor syntax errors. Hopefully the spirit of the structure is understood.

Categories