将选定的数组放入列表框中
本文关键字:列表 数组 | 更新日期: 2023-09-27 18:33:03
我想实现以下功能:当用户从下拉列表中选择电影并单击"添加到购物车"按钮时,该电影将添加到下面的列表框中。
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);
}
它给了我一些错误,我不知道该怎么做?错误是索引超出数组的范围?
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"
};
只需设置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;
> 使用 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);
}