我的网页中有一个 ListBox(我使用的是 ASP.NET Web Form 4),当我想将这些 ListBox 的项目转换为字符串数组时,它不起作用, 我使用这段代码:
protected void btnSend_Click(object sender, EventArgs e)
{
String[] a= ListBox1.Items.Cast<String>().ToArray();
}
当我点击 btnSend 并通过 Chrome 开发工具(在控制台选项卡中)检查它时,我收到如下错误:
Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to type 'System.String'
为什么会发生这种情况,我该如何解决?
请您参考如下方法:
ListBox.Items 集合包含 ListItems .
var texts = ListBox1.Items
.Cast<ListItem>()
.Select(item => item.Text)
.ToArray();
