不能用ListBox项填充数组
本文关键字:填充 数组 ListBox 不能 | 更新日期: 2023-09-27 18:05:18
这是一个我想在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;
}
}
但是ListBox Asp。Net ListBox不像WinForms ListBox,所以:
lstPeople.Items.CopyTo(names, 0);
抛出以下错误:
源数组中至少有一个元素不能向下强制转换为目标数组类型。
我试了很多,但找不到一个方法。请帮助。
在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);