c# - 数组值到列表框

标签 c# asp.net arrays sorting listbox

我有以下代码。

我正在尝试将值插入到列表框中,然后能够按字母顺序对这些值进行求值并将它们重新显示在同一个列表框中。出于某种原因代码不起作用(没有错误 - 就在我按下按钮时列表框清除)

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());
    }

}

最佳答案

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

像下面那样做:

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正在制造问题。

关于c# - 数组值到列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16712273/

相关文章:

c - 如何将文件中的文本放入数组中

javascript - 数组中的对象 数组中的对象 数组中的对象 JavaScript - 搜索

javascript - 需要有关使用 Javascript 搜索对象的帮助

javascript - 为什么验证不会在客户端失败但在服务器端失败?

c# - Entity Framework 访问数据库方法

asp.net - 导航菜单 - 渲染分隔管道字符

c# - 如何从.net 将 PDF 发送到网络打印机?

c# - 降级 Xamarin.Android

c# - 如何在共享主机环境中运行 RavenDB?

c# - 应用设计5年