0

如何Listbox在 C# 中使用 Form 的构造函数从数组中填充数据?到目前为止,这就是我在 Name Class 中所拥有的

String[,] strSpecialCakeName = {
                               {"Holiday Cake at", "$18"},
                               {"Birthday Cake at", "$25"},
                               {"Wedding Cake at", "$40"},
                               {"Super Hero Cake at", "$30"}
                               };

这就是我的表格

public partial class frmLabSeven : Form
{
    private string[,] strSpecialCakeName = new string[4, 2];

    public frmLabSeven()
    {
        InitializeComponent();

        strSpecialCakeName [0, 0] = "Holiday Cake at $18";
        strSpecialCakeName [1, 1] = "Birthday Cake at $25";
        strSpecialCakeName [2, 2] = "Wedding Cake at $40";
        strSpecialCakeName [3, 3] = "Super Hero Cake at $30";
    }
}

我知道我可以在表单上直接使用 Collection in Item,但这不是我想要做的。我只是不知道如何使用数组让数据显示在列表框中。

4

2 回答 2

2

您需要注意的第一件事是您的数组如下所示:

strSpecialCakeName[0,0] = "Holiday Cake at"
strSpecialCakeName[0,1] = "$18"
strSpecialCakeName[1,0] = "Birthday Cake at"
strSpecialCakeName[1,1] = "$25"
strSpecialCakeName[2,0] = "Wedding Cake at"
strSpecialCakeName[2,1] = "$40"
strSpecialCakeName[3,0] = "Super Hero Cake at"
strSpecialCakeName[3,1] = "$30"

您可以使用 for 语句将其添加到列表框中:

for (int i = 0; i < 4; i++)
{
    listBox1.Items.Add(strSpecialCakeName[i, 0] + " " + strSpecialCakeName[i, 1]);
}
于 2012-11-16T01:20:07.547 回答
1

遍历这两个维度会相当简单,但我不确定它是否会给你你所想的。注意@Mark Hall 评论。

for (int i = 0; i < strSpecialCakeName.GetLength(0); i++)
    lstTest.Items.Add(strSpecialCakeName[i, 0]);
for (int i = 0; i < strSpecialCakeName.GetLength(1); i++)
    lstTest.Items.Add(strSpecialCakeName[0, i]);

另外,请注意,由于索引超出了声明数组的范围,构造函数中的赋值会出错。

于 2012-11-16T01:22:32.950 回答