繁体   English   中英

如何从第一个组合框中获取SelectedValue以填充c#winforms中第二个组合框中的数据

[英]How to get SelectedValue from first combobox to fill data in second combobox in c# winforms

我在我的一个c#WinForms项目中有2个ComboBox,首先包含父类别,并且基于在第一个组合框中选择的类别,我需要在第二个组合框中填充它们的子类别。

下面是我用来填充First comboBox的代码。

private DataTable FillProductGroupID(int ParentID = -1)
        {
            DataTable dt = new DataTable();
            using (SqlConnection connection = new SqlConnection(@"server=***; uid=***; pwd=***; database=lowprice"))
            {
                try
                {
                    using (SqlCommand command = new SqlCommand("user_GetAllProductGroup", connection))
                    {
                        connection.Open();
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddWithValue("@ParentID", ParentID);
                        SqlDataAdapter adapter = new SqlDataAdapter(command);

                        adapter.Fill(dt);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    connection.Close();
                }
            }
            return dt;
        }

这是我的FormLoad事件,其中第一个组合框的绑定发生。

 cbParentCategories.DataSource = FillProductGroupID();
            cbParentCategories.DisplayMember = "Name";
            cbParentCategories.ValueMember = "Id";

这是我的第一个组合框的SelectedIndexChangedEvent,我通过它填充第二个组合框。

cbChildCategories.DataSource = 
FillProductGroupID(int.Parse(cbParentCategories.SelectedValue.ToString())); //Form Load Error Here.
            cbChildCategories.DisplayMember = "Name";
            cbChildCategories.ValueMember = "Id";

在表单加载时它只是说, Input string was not in a correct format

我有两个问题:

  1. 为什么它在FormLoad上检查SelectedIndexChangedEvent的selectedValue,它应该是我选择第一个组合框时。
  2. 什么是在第一个组合框的selectedindexchanged事件中获得第一个组合框的选定值的正确方法。

任何人都可以帮我根据第一个组合框的选择填充子类别。

下面这行

 cbParentCategories.DataSource = FillProductGroupID();

导致SelectedIndexChangedEvent触发事件。并且所选项目无效以转换为int。 所以而不是使用SelectedIndexChangedEvent 你可以尝试使用

SelectionChangeCommitted事件

仅当用户更改combobox的选定项目时才会调用此事件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM