在c#中将选定的列表框(绑定)项保存到数组中


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是object类型的,因此需要对结果进行强制类型转换。

假设您只将字符串放入列表框中,您可以使用(记住引用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,
}

SelectedItems是Object的集合,那么为了使用CopyTo的方法,chkItems必须是Object类型的数组(即object[])。

否则,您可以使用LINQ来转换,例如转换为字符串列表:

var selectedList = ltbxInterests.SelectedItems.OfType<object>()
                                              .Select(x => x.ToString()).ToList();

您可以查看> chkItems的Type

最新更新