C# 仅当按下向下键时才能获取组合框selectedValue

C# 仅当按下向下键时才能获取组合框selectedValue,c#,.net,wpf,combobox,C#,.net,Wpf,Combobox,我制作了一个WPF自动完成组合框,我面临的问题是,当我按下向下键时,我只能获得组合框的SelectedValue 问题出在下面的BindComboBox方法中,comboBox5.SelectedValue仅在按下向下键时有效 public void BindComboBox3(ComboBox comboBox3) //BatchCombobox { SqlDataAdapter da = new SqlDataAdapter("Select id,batch_id

我制作了一个WPF自动完成组合框,我面临的问题是,当我按下向下键时,我只能获得组合框的SelectedValue

问题出在下面的BindComboBox方法中,comboBox5.SelectedValue仅在按下向下键时有效

 public void BindComboBox3(ComboBox comboBox3) //BatchCombobox
    {
        SqlDataAdapter da = new SqlDataAdapter("Select id,batch_id FROM batch where product_id_fk='" + Convert.ToInt32(comboBox5.SelectedValue) + "' and left_qty>0", con);
        DataSet ds = new DataSet();
        da.Fill(ds, "batch");
        comboBox3.ItemsSource = ds.Tables[0].DefaultView;
        comboBox3.DisplayMemberPath = ds.Tables[0].Columns["batch_id"].ToString();
        comboBox3.SelectedValuePath = ds.Tables[0].Columns["id"].ToString();
    }
但是在下面的代码comboBox5.SelectedValue正常工作

private void comboBox5_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        comboBox3.IsEnabled = true;
        BindComboBox3(comboBox3); //Problem is in this Function

        con.Open();
        SqlCommand cmd1 = new SqlCommand("SELECT med_type,fk_com_id FROM products where p_id_pk='" + Convert.ToInt32(comboBox5.SelectedValue) + "'", con);

        SqlDataReader med_oftype = null;

        med_oftype = cmd1.ExecuteReader();

        while (med_oftype.Read())
        {
            get_med_type = med_oftype["med_type"].ToString();
            cmpny_id = Convert.ToInt32(med_oftype["fk_com_id"]);
        }

        con.Close(); 

    }

private void ProductsComboBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (((ComboBox)sender).Text != "")
        {
            SqlDataAdapter da = new SqlDataAdapter("Select p_id_pk,p_name FROM products", con);
            DataSet ds = new DataSet();
            da.Fill(ds, "products");
            comboBox5.ItemsSource = ds.Tables[0].DefaultView.RowFilter = "p_name like '" + ((ComboBox)sender).Text + "'+'%'";
            comboBox5.ItemsSource = ds.Tables[0].DefaultView;
            comboBox5.DisplayMemberPath = ds.Tables[0].Columns["p_name"].ToString();
            comboBox5.SelectedValuePath = ds.Tables[0].Columns["p_id_pk"].ToString();
        }
        else
        {
            comboBox5.ItemsSource = null;
        }
    } 
总结是,在一个事件处理程序中,comboBox5.SelectedValue起作用,而在另一个Combox5.SelectedValue不起作用。不知道是什么导致了这个问题

  • 如果您可以共享您的.xaml代码,这将非常有用
  • 另外,如果您可以澄清为什么将(comboBox3)作为参数发送 尽管它在视图中的任何位置都可以访问
  • 作为快速解决方案,您可以将SelectedValue作为参数传递给 bindcombox3方法

您能否更好地解释一下您试图用此代码实现的目标?combox5中的选定值为您提供检索输入,并使用..填充Combox3?更改Combobox5选择时,将根据Combobox5的选定值填充Combox3,这正是我试图实现的,但combox5。Selectedvalue在BindComBox3方法中不起作用。您是否尝试调试BindComBox3方法?
Convert.ToInt32(comboBox5.SelectedValue)
的值是多少?一个好的做法是为
Convert.ToInt32(comboBox5.SelectedValue)
之类的值声明一个变量,以使代码更清晰、可读性更好。