无法将类型为“System.Data.DataRowView”的对象强制转换为“System.String”。

问题描述:

我尝试从列表框中读取所有选择项并将其保存到列表中。但它显示错误无法将类型'System.Data.DataRowView'的对象强制转换为'System.String'。



I try to read all the selecteditem from a listbox and save it into a list. But it showing the error "Unable to cast object of type 'System.Data.DataRowView' to type 'System.String'."

List<string> Stringlist = new List<string>() ;

foreach (string selectedItem in ListBox.SelectedItems)
{
      Stringlist .Add(selectedItem);
}





请帮助,thkz



please help, thkz

使用此代码改为获取特定列表框中的所有选定值,例如listbox1:



Use this code instead to fetch all the selected values in a particular listbox, say listbox1 :

List<string> Stringlist = new List<string>();
        for (int i = 0; i < ListBox1.Items.Count; i++)
        {
            if (ListBox1.Items[i].Selected == true)
            {
                Stringlist.Add(ListBox1.Items[i].ToString());
            }
        }</string></string>





Listbox.selecteditem不是字符串,因此存在转换错误...

使用上面的代码,我想你会得到想要的结果..



谢谢



Listbox.selecteditem is not string so the conversion error was there...
Use the above code and I think you will get the desired result..

Thanks


看看文档 [ ^ ],此集合不是一组 string s。
Look at the documentation[^], this collection is not a set of strings.


查看文档 [ ^ ],此集合不是一组字符串 s。
Look at the documentation[^], this collection is not a set of strings.