I'm making a 2d array of buttons, and want its tag to be its array position, including the starting 0s and ending 0s (e.g 01 or 2002)... is this possible?
Button[,] buttonGrid = new Button[11, 21];
Button gridButton = new Button
{
Tag = int.Parse(yIndex.ToString() xIndex.ToString()),
BackColor = Color.LightGray,
Enabled = true,
Size = new Size(size, size),
Location = new Point(25, 25)
};
I used a for loop to loop through each element in the array thats where the x and y index come from.
this will return 1,2,3 - 9 in the first row then 10, 11, 12, so on. but I want it to be 01, 02, 03 or 020.
CodePudding user response:
If you need preceding zeros in your int
, I would suggest you keep the position as a string
. When you need to calculate it, just convert it to int
temporarily and perform the calculations. You can assign anything in the Tag
.
CodePudding user response:
You should probably not rely on string concatenation to create the tags. since you have no idea if "111" means x=1, y=11
or x=11, y=1
Tags are used internally to distinguish UI objects. Normally when converting two coordinates to a single index you would do a calculation like
var i = yIndex * width xIndex;
and this can be reversed:
var yIndex = i / width;
var xIndex = i - yIndex * width;
If you want the number to be in the format XXYY, then you can simply use 100 as the width. If you want to convert this to a text-label you can use a format specifier when converting it to string, i.e. i.ToString("0000")