将数组值放入列表框中

5
我有以下代码。
我试图将值插入到列表框中,然后能够按字母顺序重新排序这些值并在同一列表框中重新显示它们。但出于某种原因,代码不起作用(没有错误-只是当我按按钮时列表框就被清空了)。
protected void sortButton_Click(object sender, ImageClickEventArgs e)
{
    string[] movieArray = new string [cartListBox.Items.Count];

    for (int i = 0; i < cartListBox.Items.Count; i++)
    {
        movieArray[i] = cartListBox.Items[i].ToString();
    }

    Array.Sort(movieArray);

    cartListBox.Items.Clear();

    for (int i = 0; i < cartListBox.Items.Count; i++)
    {
        cartListBox.Items.Add(movieArray[i].ToString());
    }

}
4个回答

10

我认为问题出在最后一个循环中。

请按照以下方式进行操作:

cartListBox.Items.Clear();

    for (int i = 0; i < movieArray.Length; i++)
    {
        cartListBox.Items.Add(movieArray[i].ToString());
    }

当你要清空 cartListBox.Items.Clear();时,不应该像循环计数器一样使用它,如:for (int i = 0; i < cartListBox.Items.Count; i++)

cartListBox.Items.Count导致了问题。


啊,谢谢!我现在明白了,当我清空列表框项目时,列表框的项数将重置为0 :) 谢谢! - Anthony Johnson

1
您可以通过更现代的方式避免所有循环和错误,方法如下:
var items = cartListBox.Items
    .Select(item => item.ToString())
    .OrderBy(x => x);

cartListBox.Items.Clear();

cartListBox.Items.AddRange(items);

0
cartListBox.Items.Count // is 0 length

在前一步中,您正在进行的是:

cartListBox.Items.Clear(); 

0

使用AddRange将movieArray添加到listbox中

  • carListBox.Items.AddRange(movieArray);

要进行排序,只需将 sorted 设置为 true 即可。

  • carListBox.Sorted=true;

完整代码如下

  • carListBox.Items.AddRange(movieArray);
  • carListBox.Sorted=true;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接