Fill ListBox from selected items of another listbox when LINQ filled the first ListBox RRS feed

  • Question

  • I have filled a ListBox using LINQ as follows:

    private CateringDataContext Db = new CateringDataContext();

    private void Form1_Load(object sender, EventArgs e)


    var allSides = from foodItem in Db.FoodItems

    where foodItem.FoodType.Equals("Side")

    select foodItem;

    foodItemBindingSource2.DataSource = allSides;



    I have a button that when I click it, I want it to fill another ListBox with the SelectedItems from the first ListBox. I have tried the following code:

    int rowSide = 0;

    Object[] valueSide = new Object[SideListBox1.SelectedItems.Count];

    foreach (Object dataRowSide in SideListBox1.SelectedItems)


    valueSide[rowSide] = ((DataRowView)dataRowSide).Row.ItemArray[1];





    I get an error titled "InvalidCastException was unhandled" - that says:

    "Unable to cast object of type 'CateringManagement2.FoodItem' to type 'System.Data.DataRowView'."


    Would anyone show me what I am doing wrong - this same code works if I fill the first ListBox from a DataSet rather than using LINQ.




    Saturday, February 2, 2008 3:53 PM