两个连接的组合框不工作

时间:2016-03-30 17:56:24

标签: c# wpf if-statement combobox

我有两个组合框。当我更改类别组合框的值时,它应该自动更改大小组合框的值。

private void New_Item_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'pitauzDBDataSet.Item' table. You can move, or remove it, as needed.
    this.itemTableAdapter.Fill(this.pitauzDBDataSet.Item);

    cbx_product_category.Items.Add("Pita");
    cbx_product_category.Items.Add("Drinks");
    cbx_product_category.Items.Add("Other Foods");
}

private void cbx_product_category_SelectedIndexChanged(object sender, EventArgs e)
{
    string ItemSelected = cbx_product_category.SelectedIndex.ToString();
    if(ItemSelected == "Pita")
    {
        cbx_product_size.Items.Clear();
        cbx_product_size.Items.Add("Small");
        cbx_product_size.Items.Add("Regular");
        cbx_product_size.Items.Add("Large");
        cbx_product_size.Items.Add("Very-Large");
    }
    if(ItemSelected == "Drinks")
    {
        cbx_product_size.Items.Clear();
        cbx_product_size.Items.Add("0.5L");
        cbx_product_size.Items.Add("1L");
        cbx_product_size.Items.Add("1.5L");
    }
    if (ItemSelected == "Other Foods")
    {
        cbx_product_size.Items.Clear();
        cbx_product_size.Items.Add("Half");
        cbx_product_size.Items.Add("Full");
    }
}

没有任何错误。只是逻辑不起作用。

1 个答案:

答案 0 :(得分:3)

问题出在这一行

string ItemSelected = cbx_product_category.SelectedIndex.ToString();

SelectedIndex将返回一个数字,而不是项目本身。

你想要做的是:

var item = cbx_product_category.SelectedItem;
string ItemSelected = "";
if(item != null)
    ItemSelected = item.ToString();

*注意,因为这是在选择更改事件中,SelectedItem不应该返回null,但确实不会确实