【发布时间】:2014-01-23 08:53:07
【问题描述】:
我需要将二维数组的内容打印到一个名为 txtExecute 的文本框,格式如下:
Mon Tue Wed Thu Fri
Week 1 1 2 3 4 5
Week 2 6 7 8 9 10
Week 3 11 12 13 14 15
Week 4 16 17 18 19 20
我得到了正确的星期和日期的格式,但我不知道如何得到完全一样的数组值。到目前为止,这是我的代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[,] productsArray = new int[4, 5];
private void AddValuesToArray()
{
txtExecute.Text = "Filling the array with user input..." + "\r\n\r\n";
String value;
int num;
for (int week = 0; week < productsArray.GetLength(0); week++)
{
for (int day = 0; day < productsArray.GetLength(1); day++)
{
value = Microsoft.VisualBasic.Interaction.InputBox("Enter value for " + day + " of week " + week, "Enter Value");
try
{
while (!(int.TryParse(value, out num)))
{
MessageBox.Show("Not a valid number, try again.");
value = Microsoft.VisualBasic.Interaction.InputBox("Enter a number", "Enter Number");
}
}
catch (Exception)
{
MessageBox.Show("Value entered is not in a valid format");
}
productsArray[week, day] += int.Parse(value);
}
}
txtExecute.Text += "The product allocation is as follows:" + "\r\n\r\n";
}
private void ArrayFormat()
{
txtExecute.Text += "\t" + "Mon" + "\t" + "Tue" + "\t" + "Wed" + "\t" + "Thu" + "\t" + "Fri" + "\r\n";
for(int week = 0; week < productsArray.GetLength(0); week++)
{
txtExecute.Text += "Week " + week + "\t" +"\r\n";
for (int day = 0; day < productsArray.GetLength(0); day++)
{
txtExecute.Text += productsArray[0, 0];
}
}
}
private void btnExecute_Click(object sender, EventArgs e)
{
AddValuesToArray();
ArrayFormat();
}
}
}
这是我得到的输出:
Mon Tue Wed Thu Fri
Week 0
1111Week 1
1111Week 2
1111Week 3
1111
我意识到我只输出了 1 个元素,我将不得不打印出其余的元素,但我想先解决这个问题。
【问题讨论】:
-
我强烈建议为此使用DataGridView。否则,最好的办法是使用等宽字体并使用空格来排列。 (如果您尝试使用标签,您将陷入痛苦的世界......)
标签: c# arrays multidimensional-array output