Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Can';t使用列表框项填充数组_C#_Asp.net_Listbox_Listitem - Fatal编程技术网

C# Can';t使用列表框项填充数组

C# Can';t使用列表框项填充数组,c#,asp.net,listbox,listitem,C#,Asp.net,Listbox,Listitem,下面是我想在web表单中使用的windows表单: // 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]; lstPeo

下面是我想在web表单中使用的windows表单:

// 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;
    }
}
引发以下错误:

源数组中至少有一个元素无法向下转换到 目标数组类型


我试了很多,但找不到解决办法。请提供帮助。

在WebForms
列表框中
包含类型为
ListItem
的项,因此首先应以不同的方式声明数组:

ListItem[] names = new ListItem[numPeople];
lstPeople.Items.CopyTo(names, 0);
还要注意,
names[i]
不再是字符串。决定是否要使用文本或值,并进行适当更改。例如,对于
文本
(您可能希望在此处使用
string.Format
):


为什么要在这里添加WPF标记?我看不出有任何联系。谢谢!我尝试了ListItem、ListItemCollection和一切让我的生活复杂化的东西,但答案就是这么简单。我还必须将
随机化器
行从
修改为
,以使事情顺利进行。无需修改
名称[i]
,但它不会按应有的方式对组进行排序。
ListItem[] names = new ListItem[numPeople];
lstPeople.Items.CopyTo(names, 0);
 lstResult.Items.Add(groupNum.ToString() + "    " + names[i].Text);