string[] chkItems = new string[4];
string[] str = new string[4];
str[0] = txtID.Text;
str[1] = txtName.Text;
str[2] = txtEmail.Text;
itemCount = ltbxInterests.SelectedItems.Count;
for (int i = 0; i <= itemCount; i++)
{
ltbxInterests.SelectedItems.CopyTo(chkItems, 0);
// here it is returning an exception
//"Object cannot be stored in an array of this type."
}
请帮助我如何摆脱此异常
最佳答案
这里有几个问题,chkItems 被定义为长度 4,因此如果您尝试放入超过 4 个项目,则会出现异常。源数组 SelectedItems 是对象类型,因此您需要转换结果。
假设您仅将字符串放入可以使用的列表框中(请记住引用 System.Linq)
string[] str = new string[4];
str[0] = txtID.Text;
str[1] = txtName.Text;
str[2] = txtEmail.Text;
string[] chkItems = ltbxInterests.SelectedItems.OfType<string>().ToArray();
如果您想限制为前 4 项,您可以将最后一行替换为
string[] chkItems = ltbxInterests.SelectedItems.OfType<string>().Take(4).ToArray();
您还可以缩短代码以使用数组初始值设定项(但这将使 str 长度为 3,因为您只有 3 个项目):
string[] str = new [] {
txtID.Text,
txtName.Text,
txtEmail.Text,
}
关于c# - 将选定的列表框(绑定(bind))项目保存到 C# 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6772197/