uzi42tmp
uzi42tmp

Reputation: 291

Adding elements from a ListBox to a List

I have a ListBox with Integers in it that gets them from a SQL database. Now I wanted to put these elements into a List when they get selected but somehow it won't work. Here is the code:

List<Int32>typeElements = new List<Int32>();

if(form1.listBox.SelectedIndex != -1)   
{
    foreach (var selectedItem in form1.listBox.SelectedItems)
    {
        typeElements.Add(selectedItem);
    }
}

He tells me he can't convert object to int and that the method has some invalid arguments. How to handle that?

Upvotes: 0

Views: 99

Answers (2)

Pranav Bilurkar
Pranav Bilurkar

Reputation: 965

Try this (using System.Linq):

OfType() is an extension method, so you need to use System.Linq

List<Int32> selectedFields = new List<Int32>();
selectedFields.AddRange(listbox.CheckedItems.OfType<Int32>());

Or just do it in one line:

List<Int32> selectedFields = listbox.CheckedItems.OfType<Int32>().ToList();

Upvotes: 0

Steve
Steve

Reputation: 216243

ListBox.SelectedItems is a collection of objects. You can't simply take an element from this collection and add it to a typed list of integers. You need a conversion

typeElements.Add(Convert.ToInt32(selectedItem));

If you want to use Linq and the IEnumerable extensions then you could write your loop in one line

// List<Int32>typeElements = new List<Int32>();
List<Int32> typeElements = form1.listBox.Items.Cast<int>().ToList();

EDIT:
Following your comment then you need to extract the Integer element from the DataRowView

DataRow row = (selectedItem as DataRowView).Row;
typeElements.Add(row.Field<int>("NameOfYourDataBaseIntegerField"));

Upvotes: 2

Related Questions