【问题标题】:Populate a ComboBox from ListBox with LINQ使用 LINQ 从 ListBox 填充 ComboBox
【发布时间】:2019-05-12 23:45:17
【问题描述】:

我在网上找不到我的问题的答案..

我有一个使用 LINQ(存储过程)填充 SQL 表的 ListBox

我有一个 ComboBox,它也使用 LINQ(存储过程)填充了一条 SQL 语句 问题是 ComboBox 的存储过程需要来自 ListBox 的输入,而我似乎无法正确转换它。

这是我的 ListBox 的填充方式:

private void NouvelleReservation2_Load(object sender, EventArgs e)
    {
        ExamenSGBDEntities oExamenSgbdEntities = new ExamenSGBDEntities();
        listBoxRestaurant.DataSource = oExamenSgbdEntities.SelectAllRestaurants();
        listBoxRestaurant.DisplayMember = "RESTO";
        listBoxRestaurant.ValueMember = "idRestaurants";
        listBoxRestaurant.SelectedIndex = 0;
    }

这是我的 ComboBox 的填充方式:

private void listBoxRestaurant_SelectedIndexChanged(object sender, EventArgs e)
    {
        ExamenSGBDEntities oExamenSgbdEntities = new ExamenSGBDEntities();
        comboBoxTables.DataSource =
            oExamenSgbdEntities.SelectTablesByRestaurant(listBoxRestaurant.Items.Cast<Restaurant>()); //Here is where i'm struggling... I need to give the "idRestaurant" from the ListBox as parameter for my stored procedure.
        comboBoxTables.DisplayMember = "TABLECHAISE";
        comboBoxTables.ValueMember = "idTables";
    }

我尝试在 DataRowView 中转换 selectedItem,然后再转换为整数,但没有成功。 已尝试您现在在代码中看到的内容,但无法使其正常工作。

有人可以帮帮我吗?

提前致谢!

【问题讨论】:

    标签: c# winforms linq combobox listbox


    【解决方案1】:

    而不是通过:

    listBoxRestaurant.Items.Cast()...

    你试过了吗?

    listBoxRestaurant.SelectedItem

    【讨论】:

    • 我试过了。但我的 Item 是一个对象,我只需要它的 ID(我需要一个 int)
    • 哦-对-我的错。您需要将其转换为您的班级并从中获取 ID... var selectedItem = (Restaurant)listBox.SelectedItem。然后使用 selectedItem.Id;
    • 我认为这可行,但在调用演员表时仍然出现错误: System.InvalidCastException: 'Impossible d'effectuer un cast d'un objet de type 'Reservation.SelectAllRestaurants_Result' en type 'Reservation .餐厅'。'
    • 我发现了我的错误。我将演员更改为 SelectAllRestaurants_Result 并且它起作用了。感谢您的帮助!
    【解决方案2】:

    您似乎正在尝试将餐厅列表传递给您的查询,但您说您需要 id 值?如果您需要一个 id 值(如查询接受一个输入),您应该使用类似:

    comboBoxTables.DataSource = oExamenSgbdEntities.SelectTablesByRestaurant(listBoxRestaurant.Items.Cast<Restaurant>().First().idRestaurant);
    

    您可能会遇到转换错误,因为它无法将 IEnumerable 转换为 int。

    您也可以将 SelectedItem 转换为 Restaurant,然后按照 Jon Vote 所说的那样获取 id。

    【讨论】:

    • 感谢您的回答。我试过但得到以下错误: System.InvalidCastException: 'Impossible d'effectuer un cast d'un objet de type 'Reservation.SelectAllRestaurants_Result' en type 'Reservation.Restaurant'.'。
    【解决方案3】:

    不要尝试投射选定的列表项。而是使用选定的值:

    listBoxRestaurant.SelectedValue
    

    然后您可以通过此 ID 值从数据库中加载餐厅并将其传递给您的 SelectTablesByRestaurant() 函数。

    【讨论】:

    • 感谢您的回答。仍然不起作用,因为我得到一个对象并且只需要 int 中该对象的一个​​元素
    • 您需要将SelectedValue 转换为int,然后使用它从数据库中获取餐厅对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 2012-11-18
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 2017-05-23
    • 2013-06-11
    相关资源
    最近更新 更多