简体   繁体   中英

How do I use the Form's constructor to populate a List Box with data from an Array

How do I use my Form's constructor to populate a Listbox with data from an Array in C#? So far this is what I have in my Name Class

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

And this is what I have in my Form

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";
    }
}

I know I can use the Collection in Item right on the Form, but that is not what I want to do. I just don't know how to get the data to show on the List Box using Arrays.

First thing you need to be aware of is that your array looks like this:

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"

You can use a for statement to add it to your listbox:

for (int i = 0; i < 4; i++)
{
    listBox1.Items.Add(strSpecialCakeName[i, 0] + " " + strSpecialCakeName[i, 1]);
}

Iterating through both dimensions would be fairly simple, but I'm not sure it's going to give you what you think it is. Note @Mark Hall comment.

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]);

Also, note that your assignments in the constructor are going to error due to index being outside the bounds of the declared array.

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