Click here to Skip to main content
16,018,158 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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'."

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

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


please help, thkz
Posted

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

C#
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 is not string so the conversion error was there...
Use the above code and I think you will get the desired result..

Thanks
 
Share this answer
 
Look at the documentation[^], this collection is not a set of strings.
 
Share this answer
 
Look at the documentation[^], this collection is not a set of strings.
 
Share this answer
 
Convert from object to string as
C#
List<string> Stringlist = new List<string>() ;
string strItem =string.Empty;
foreach (object selectedItem in ListBox.SelectedItems)
{
     strItem = selecteditem as String;
      Stringlist .Add(strItem );
}
</string></string>


or check this link

http://stackoverflow.com/questions/1586078/getting-all-selected-values-from-an-asp-listbox[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900