Im trying to iterate of a two dimensional array of Buttons like this
Button[,] buttonsArray = new Button[row,col];
foreach(Button button in buttonsArray)
{
button = new Button();
}
but im getting the next error: "Error Cannot assign to 'button' because it is a 'foreach iteration variable'"
what im doing worng?
The compiler message says it all - you're trying to assign a new value to button
, but the iteration variable (the one declared by a foreach
statement) is read-only. A foreach
loop can only be used to iterate over the existing content in a collection - it can't be used to change the content in a collection. (Note that if you change the data within an object referred to by the collection, that's not actually changing the value in the collection, which would just be a reference to the object.)
I suspect you really want something more like this:
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
buttonsArray[i, j] = new Button();
}
}
See more on this question at Stackoverflow