ComboBox索引已更改

时间:2016-09-15 06:36:44

标签: c# .net winforms combobox datatable

需要知道:我正在使用Visual Studio和C#中的Windows窗体。

我有5个comobobox,我从SQL填充数据库中可用的部分。编码的一部分,一个使用DataTable并将comboBox的DataSource设置为该DataTable。

通过我的SQL查询在同一个DataTable中,我列出了列表中部件的成本。我想要做的是从下拉列表中选择哪一部分,相关价格必须显示在旁边的文本框中。

我正在尝试使用comboBox1_SelectedIndexChanged,但我遇到的问题是,DataSource在表单的初始加载时设置为DataTable,它会得到拾取为索引更改并且comboBox1_SelectedIndexChanged想要运行。但是在这个时间点,SelectedIndex值是 null ,因为它仍然加载,导致它给我一个异常播放错误。

我该如何解决这个问题?

DataTable SparePart = new DataTable()在函数外部声明为“公共”,以便comboBox1_SelectedIndexChanged可以访问它。

然后我将此代码填充到comboBox

                //Read Status info from DB
            SqlDataAdapter SparePartReader = new SqlDataAdapter(SQLSparePartDropbox);
            SparePartReader.Fill(SparePart);


            comboBoxFinJCSpares1.DataSource = SparePart;
            comboBoxFinJCSpares1.DisplayMember = "DisplayMember";
            comboBoxFinJCSpares1.ValueMember = "PartID";

                //Set Combox1 affiliated Cost value to cost textbox
            int ComBo1PartID = (int)comboBoxFinJCSpares1.SelectedValue;
            string CostPrice = (from DataRow dr in SparePart.Rows
                                where (int)dr["PartID"] == ComBo1PartID
                                select (string)dr["PartCost"]).FirstOrDefault();
            textBoxFinJCCost1.Text = CostPrice.ToString();

然后我对comboBoxFinJCSpares1_SelectedIndexChanged

有这个
            //Set Combox1 affiliated Cost value to cost textbox
        int ComBo1PartID = (int)comboBoxFinJCSpares1.SelectedValue;
        string CostPrice = (from DataRow dr in SparePart.Rows
                            where (int)dr["PartID"] == ComBo1PartID
                            select (string)dr["PartCost"]).FirstOrDefault();
        textBoxFinJCCost1.Text = CostPrice.ToString();

enter image description here

2 个答案:

答案 0 :(得分:0)

解决方案就像制作一个布尔变量一样简单,并将其命名为formLoaded。

将其设置为false,然后在加载表单后将其设置为true。

将你的代码用于在if语句中填充组合框,并且应该这样做

干杯〜陈慈

演示:

        //Read Status info from DB
        if(formLoaded)
        {
            SqlDataAdapter SparePartReader = new SqlDataAdapter(SQLSparePartDropbox);
            SparePartReader.Fill(SparePart);


            comboBoxFinJCSpares1.DataSource = SparePart;
            comboBoxFinJCSpares1.DisplayMember = "DisplayMember";
            comboBoxFinJCSpares1.ValueMember = "PartID";

            //Set Combox1 affiliated Cost value to cost textbox
            int ComBo1PartID = (int)comboBoxFinJCSpares1.SelectedValue;
            string CostPrice = (from DataRow dr in SparePart.Rows
                            where (int)dr["PartID"] == ComBo1PartID
                            select (string)dr["PartCost"]).FirstOrDefault();
            textBoxFinJCCost1.Text = CostPrice.ToString();
        }

答案 1 :(得分:0)

谢谢大家,Marcel Hoekstra建议的“SelectedChangeCommitted”选项解决了我的问题。