1

我想实现以下功能:当用户从下拉列表中选择一部电影并单击“添加到购物车”按钮时,该电影将添加到下面的列表框中。

protected void addImageButton_Click(object sender, ImageClickEventArgs e)
{
    string[] moviesArrayString = new string[10];

    moviesArrayString[1] = "Badboy 2";
    moviesArrayString[2] = "BadBoy 3";
    moviesArrayString[3] = "The Godfather";
    moviesArrayString[4] = "Inception";
    moviesArrayString[5] = "The Shawshank Redemtion";
    moviesArrayString[6] = "Star Wars";
    moviesArrayString[7] = "The Metrix";
    moviesArrayString[8] = "King Kong";
    moviesArrayString[9] = "Point Break";
    moviesArrayString[10] = "Top Gun";


    cartListBox.Items.AddRange(moviesArrayString);
}

它给了我一些错误,我不知道该怎么做?错误是索引超出了数组的范围?

4

3 回答 3

3

C# 中的数组是从零开始的。使用从 0 到 9 的索引:

protected void addImageButton_Click(object sender, ImageClickEventArgs e)
{
    string[] moviesArrayString = new string[10];

    moviesArrayString[0] = "Badboy 2";
    moviesArrayString[1] = "BadBoy 3";
    moviesArrayString[2] = "The Godfather";
    moviesArrayString[3] = "Inception";
    moviesArrayString[4] = "The Shawshank Redemtion";
    moviesArrayString[5] = "Star Wars";
    moviesArrayString[6] = "The Metrix";
    moviesArrayString[7] = "King Kong";
    moviesArrayString[8] = "Point Break";
    moviesArrayString[9] = "Top Gun";

    cartListBox.Items.AddRange(moviesArrayString);
}

或者,您可以使用:

string[] moviesArrayString =
{
    "Badboy 2", "BadBoy 3", "The Godfather", "Inception",
    "The Shawshank Redemtion", "Star Wars", "The Matrix", "King Kong", "Point Break", "Top Gun"
};
于 2013-09-28T02:09:50.747 回答
0

只需设置DataSource而不是将项目添加到列表框中......

string[] moviesArrayString =
{
    "Badboy 2", "BadBoy 3", "The Godfather", "Inception",
    "The Shawshank Redemtion", "Star Wars", "The Matrix", "King Kong", "Point Break", "Top Gun"
};

 listBox1.DataSource = moviesArrayString;
于 2013-09-28T06:18:22.143 回答
-1

使用 List<> 或 ArrayList 代替 string[]。

例如:

ArrayList lst=new ArrayList();
lst.Add("badboy2");
lst.Add("badbo32");
lst.Add("badb2");
lst.Add("bboy2");
lst.Add("bad2");
foreach(string str in lst)
{
cartListBox.Items.Add(str);
}
于 2013-09-28T03:03:42.120 回答