无法使用ListBox项填充数组

时间:2014-05-27 14:59:14

标签: c# asp.net listbox listitem

这是我希望在网络表单中使用的窗体:

// Assign the people to groups.
private void btnAssign_Click(object sender, EventArgs e)
{
    // Get the names into an array.
    int numPeople = lstPeople.Items.Count;
    string[] names = new string[numPeople];
    lstPeople.Items.CopyTo(names, 0);

    // Randomize.
    Randomizer.Randomize<string>(names);

    // Divide the names into groups.
    int numGroups = int.Parse(txtNumGroups.Text);
    lstResult.Items.Clear();
    int groupNum = 0;
    for (int i = 0; i < numPeople; i++)
    {
        lstResult.Items.Add(groupNum.ToString() +
            "    " + names[i]);
        groupNum = ++groupNum % numGroups;
    }
}

但ListBox Asp.Net ListBox与WinForms ListBox不同,所以该行包含:

lstPeople.Items.CopyTo(names, 0);

引发以下错误:

  

源数组中至少有一个元素无法转换为   目标数组类型。

我尝试了很多,但无法找到方法。请帮忙。

1 个答案:

答案 0 :(得分:1)

在WebForms ListBox中包含ListItem类型的项目,因此首先应该以不同的方式声明数组:

ListItem[] names = new ListItem[numPeople];
lstPeople.Items.CopyTo(names, 0);

另请注意,names[i]不再是字符串。决定是否要使用文本或值,并进行适当更改。例如。对于Text(顺便说一下,您可能希望在此使用string.Format):

 lstResult.Items.Add(groupNum.ToString() + "    " + names[i].Text);