首页 > 解决方案 > 如何在标签中显示二维数组的值?

问题描述

我有一个二维数组,如下所示。我想在 Windows 窗体上使用标签显示它,因此它采用表格格式(行和列)。我该如何实现?

string[,] map = new string[10, 10] 
{ 
    { ".", ".", ".", ".", ".", ".", ".", ".", ".", "." }, 
    { ".", ".", ".", ".", ".", ".", ".", ".", ".", "." }, 
    { ".", ".", ".", ".", ".", ".", ".", ".", ".", "." }, 
    { ".", ".", ".", ".", ".", ".", ".", ".", ".", "." }, 
    { ".", ".", ".", ".", ".", ".", ".", ".", ".", "." }, 
    { ".", ".", ".", ".", ".", ".", ".", ".", ".", "." }, 
    { ".", ".", ".", ".", ".", ".", ".", ".", ".", "." }, 
    { ".", ".", ".", ".", ".", ".", ".", ".", ".", "." }, 
    { ".", ".", ".", ".", ".", ".", ".", ".", ".", "." }, 
    { ".", ".", ".", ".", ".", ".", ".", ".", ".", "." }
};

标签: c#winforms

解决方案


使用monospaced类似字体Consolas和向左填充空格,如下所示:

Label label = new Label();
this.Controls.Add(label);
label.Size = new Size(500, 500); // Enter custom size or use Graphics.MeasureString method to find proper size dynamically
label.AutoSize = false;
label.Font = new Font("Consolas", 8);
for (int i = 0; i < map.GetLength(0); i++)
{
    for (int j = 0; j < map.GetLength(1); j++)
    {
        label.Text += map[i, j].PadLeft(5, ' ');
    }
    label.Text += Environment.NewLine;
}

推荐阅读