简体   繁体   中英

I can't set the new line for my label

I'm having trouble to set new line for my label. My label grid.Text only show the first character, and that's it. I already set the autosize == false , but it doesn't do anything. I've been checking my code for a while now, and haven't seen anything wrong with that. I even set a temp varibale to get the value returned from the DrawMaze function, and it appears working fine for me. However, when I assign it to label grid.Text, it doesn't get a new line. Does System.Environment.NewLine is not working for Windows 7 platform ? I'm running Windows 7 with Visual Studio 2010.

MousMaze class:

  // Set up the mouseMaze grid
  public char[,] computeMaze(int width, int height)
  { 
      mouseMaze = new char[height, width];
      // set left n right wall to X
      for (int i = 0; i < height; i++)
      {
          // left
          mouseMaze[i, 0] = 'X';
          // right
          mouseMaze[i, (width - 1)] = 'X';
      }

      return mouseMaze;
  }

Form1.cs

 // Set up the mouseMaze grid
 public string DrawMaze(int width, int height, char[,] m)
 {
      string mazeString = "";

      for (int i = 0; i < height; i++)
      {
           for (int j = 0; j < width; j++)
           {
               mazeString += m[i, j];
           }
           mazeString += System.Environment.NewLine;
      }
      return mazeString;
 }

  private void newMaze_Click(object sender, EventArgs e)
  {
       string temp = "";
       gridWidth = int.Parse(width.Text);
       gridHeight = int.Parse(height.Text);

       game.SetWidth(gridWidth);
       game.SetHeight(gridHeight);
       maze = game.computeMaze(gridWidth, gridHeight);
       grid.Text = DrawMaze(gridWidth, gridHeight, maze);
  }

A label is not the right control for multi-line text. You should use a textbox instead. It allows auto-wrapping your text if desired you can use the Environment.NewLine -constant.

In DrawMaze() , if you put a breakpoint to check the content of mazeString right before return, you will find that it's filled with null character, ie '\\0' , like this:

X\0\0\0\0\0\0\0\0X\r\nX\0\0\0\0\0\0\0\0X\r\n...

That's why you can only see the first character printed in the label.

To fix this you can 1) replace the null character to space:

string mazeString = DrawMaze(gridWidth, gridHeight, maze);
grid.Text = mazeString.Replace('\0', ' ');

2) Or make sure you've filled every character in the array inside computeMaze() :

// left
mouseMaze[i, 0] = 'X';
// middle
for (int j = 1; j < width - 1; j++)
    mouseMaze[i, j] = ' ';
// right
mouseMaze[i, (width - 1)] = 'X';

Try with this line:

mazeString += "\n";

Instead of this one:

mazeString += System.Environment.NewLine;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM