问题描述:

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?

相关阅读:
Top