C# Can';t使用列表框项填充数组
下面是我想在web表单中使用的windows表单: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
// 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);