c# - 将选定的列表框(绑定(bind))项目保存到 C# 中的数组

标签 c# .net windows

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/

相关文章:

windows - 从 Windows 访问 Docker 容器文件

windows - 在 Windows 上确定 GPU 制造商

c# - 如何简化对泛型方法的调用,我创建了该方法以跨项目的不同层从一种类型转换为另一种类型

c# - .Net Release 构建工作速度比 Debug 慢

c# - 按钮 FontWeight 不起作用

.net - 将 SQL CE 数据序列化为 XML

.net - 在 VS2010 中调试故障转储

c# - 如何检测所选打印机的类型是否为点阵?

.net - 如何判断我的应用程序是否在 RDP session 中运行

r - Rstudio 版本(版本 1.3.1073) "Giant goldenrod"将 R studio 窗口移动到新显示器时出现的问题无法正确显示