我有一个组合框“ SelectionChange”事件。

这是我想做的事情:


我有两个组合框
第二个ComboBox将根据第一个Box上的选定项目显示项目
一旦选择了ComboBox1上的一项,ComboBox2应该做出反应


我的问题是当我尝试获取SelectedIndex时。

当我在确认SelectedIndex后使用ComboBox1.Text时,它返回null,因此ComboBox2不响应。

我尝试放置一个按钮来强制该事件,但它确实起作用。在释放焦点之前,SelectedIndex似乎不会改变。

这是代码片段:

if (cb_subj.SelectedIndex == ctr)
{
     cb_section.Items.Clear();
     if (connectToDB.openConnection() == true)
     {
         MySqlDataAdapter comboBoxItems_seclist = new MySqlDataAdapter();

         MySqlCommand query = new MySqlCommand(@"SELECT section_code FROM sections
                             WHERE subject = @subj", connectToDB.connection);
         query.Parameters.AddWithValue("@subj", cb_subj.Text);

         comboBoxItems_seclist.SelectCommand = query;


         System.Data.DataTable classlist = new System.Data.DataTable();

         comboBoxItems_seclist.Fill(classlist);

         foreach (System.Data.DataRow row in classlist.Rows)
         {
            string rows = string.Format("{0}", row.ItemArray[0]);
            cb_section.Items.Add(rows);
         }
       }

      break;
}


这是两个CB的XAML:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="166,12,0,0" Name="cbox_year" VerticalAlignment="Top" Width="120" SelectionChanged="cbox_year_SelectionChanged">
        <ComboBoxItem Content="1st Year / 1st Sem" />
        <ComboBoxItem Content="1st Year / 2nd Sem" />
        <ComboBoxItem Content="2nd Year / 1st Sem" />
        <ComboBoxItem Content="2nd Year / 2nd Sem" />
        <ComboBoxItem Content="3rd Year / 1st Sem" />
        <ComboBoxItem Content="3rd Year / 2nd Sem" />
        <ComboBoxItem Content="4th Year / 1st Sem" />
        <ComboBoxItem Content="4th Year / 2nd Sem" />
    </ComboBox>
    <ComboBox Height="23" HorizontalAlignment="Left" Margin="166,41,0,0" Name="cb_subj" VerticalAlignment="Top" Width="120" SelectionChanged="cb_subj_SelectionChanged" />

最佳答案

为了获得快速成功,您可以访问ComboBox1.SelectedValue或ComboBox1.SelectedItem而不是ComboBox1.Text。

您的主要问题似乎是当ComboBox1中的选择更改时,它不会直接更改ComboBox1.Text,您(即焦点)将不得不离开ComboBox1,直到更新Text。通常,您可以通过使用数据绑定而不是基于事件的方法来避免此类问题。

10-02 01:04
查看更多