You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让ComboBox的SelectionChanged事件在正确时机执行函数?

问题解决方法

核心问题原因

WPF中SelectionChanged事件触发时,cmbSubject.Text的更新滞后于选中状态的变化,导致你获取的是上一次的选中值,而非当前选中的科目。

具体修改方案

1. 重构PopulateSubtopicCombobox方法

添加参数接收选中科目,改用参数化查询过滤数据,同时用SQL的DISTINCT关键字去重(比代码循环判断更高效):

private void PopulateSubtopicCombobox(string selectedSubject = null)
{
    string connectionString = string.Format("Data Source={0}", _db);
    string queryString2;

    // 根据选中科目动态生成查询语句
    if (string.IsNullOrEmpty(selectedSubject))
    {
        // 无选中科目时,查询所有不重复的子科目
        queryString2 = "SELECT DISTINCT TopicDescription FROM tblTopic ORDER BY TopicNumber";
    }
    else
    {
        // 有选中科目时,只查询对应科目的子科目
        queryString2 = "SELECT DISTINCT TopicDescription FROM tblTopic WHERE TopicSubject = @Subject ORDER BY TopicNumber";
    }

    using (SQLiteConnection conn = new SQLiteConnection(connectionString))
    {
        conn.Open();
        using (SQLiteCommand cmd = new SQLiteCommand(queryString2, conn))
        {
            // 添加参数,避免SQL注入
            if (!string.IsNullOrEmpty(selectedSubject))
            {
                cmd.Parameters.AddWithValue("@Subject", selectedSubject);
            }

            using (SQLiteDataReader reader = cmd.ExecuteReader())
            {
                cmbSubtopic.Items.Clear();
                while (reader.Read())
                {
                    cmbSubtopic.Items.Add(reader["TopicDescription"].ToString());
                }
            }
        }
    }
}

2. 修改SelectionChanged事件处理逻辑

改用SelectedItem获取当前选中的科目(事件触发时SelectedItem已更新):

private void cmbSubject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (cmbSubject.SelectedItem != null)
    {
        string selectedSubject = cmbSubject.SelectedItem.ToString();
        PopulateSubtopicCombobox(selectedSubject);
    }
    else
    {
        // 选中项为空时,显示所有子科目
        PopulateSubtopicCombobox();
    }
}

3. 调整初始化调用

保持OnLoad中的初始化逻辑不变,仅确保调用重构后的方法:

private void OnLoad(object sender, RoutedEventArgs e)
{
    string connectionString = string.Format("Data Source={0}", _db);
    string queryString1 = "SELECT DISTINCT TopicSubject FROM tblTopic ORDER BY TopicNumber";

    // 填充科目下拉框(同样用DISTINCT去重,简化代码)
    SQLiteDataAdapter da = new SQLiteDataAdapter(queryString1, connectionString);
    DataTable dt = new DataTable();
    da.Fill(dt);
    foreach (DataRow row in dt.Rows)
    {
        cmbSubject.Items.Add(row["TopicSubject"]);
    }

    PopulateSubtopicCombobox();
}

额外优化点

  • 科目下拉框的填充也改用DISTINCT关键字,去掉冗余的循环判断。
  • 使用using语句管理数据库连接和命令,确保资源及时释放。
  • 参数化查询避免SQL注入风险,同时提升查询效率。

内容的提问来源于stack exchange,提问作者Cee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:18:50