【问题标题】:No events fire when I populate ComboBox programmatically当我以编程方式填充 ComboBox 时没有事件触发
【发布时间】:2013-03-07 21:09:02
【问题描述】:

为了让它尽可能简单:ComboBox1 绑定到一个空列表(在 Form1 加载事件处理程序中),并且有一个与 ComboBox1 关联的事件处理程序:

private void CB1_SelectedIndexChanged(object sender, EventArgs e)
{
    MessageBox.Show("Event fired");
}

private void Form1_Load(object sender, EventArgs e)
{
     CB1.DataSource = list1;
     CB1.ValueMember = "Name";
     CB1.DisplayMember = "Name";
}

表单加载完毕,CB1.SelectedIndex = -1, CB1.Text = "", CB1.Items.Count = 0

当我单击 Button1 时,会填充 list1。现在情况如下: CB1.SelectedIndex = 0, CB1.Text = "一些文本", CB1.Items.Count =196

但是,事件没有触发,尽管 SelectedIndex 从 -1 变为 0,并且我没有得到 MessageBox.Show("Event failed")。但是,当用户从列表中选择某个项目时,会触发该事件。此外,还有另一个按钮可以清除 list1,从而清除 CB1.Items。按下此按钮时,事件也会触发(SelectedIndex 从 X 变为 -1)。

我尝试使用其他事件,例如 SelectedValueChanged、TextChanged、SelectionChangeCommitted,但没有成功。

虽然这个问题有一个简单的暴力解决方法,但我仍然不明白为什么会出现这个问题,因此无法预测类似的情况。这就是为什么如果有人向我解释为什么在我描述的情况下没有触发任何事件,我将不胜感激。

【问题讨论】:

  • 你可以用你自己的事件参数自己调用它。
  • 您是否实际分配过事件? CB1.SelectedIndexChanged += new EventHandler(CB1_SelectedIndexChanged)
  • @Joel:我犯了那个错误,我已经摸不着头脑了几分钟。
  • 事件处理程序通常不是protected吗?而且我认为您应该使用更具体的EventArgs
  • @Yuck 事件处理程序通常是私有的,至少 Visual Studio 创建私有方法。 SelectedIndexChanged 事件也使用 EventArgs。

标签: c# winforms events combobox


【解决方案1】:

我的评论得到了足够的关注,所以我应该把它作为一个潜在的答案似乎是合适的。您应该确保已通过委托或在设计器中使用组合框本身的属性将事件实际分配给方法。

// Somewhere in the form load or init events
CB1.SelectedIndexChanged += new EventHandler(CB1_SelectedIndexChanged);

【讨论】:

  • @kashif:除非你对一些非常敏感的事件序列进行微调,否则应该完全没问题。有时您可能想在提交发生(验证、确认、修改?)之前在用户更改事件SelectedIndexChanged 处中断操作,但在大多数情况下,它们的行为应该相同。
  • 我认为这并不能解决他的问题。因为我希望在按钮更改组合框1的索引时调用 selectedindexchanged 事件。单击事件
【解决方案2】:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.button1.Click += new System.EventHandler(this.comboBox1_SelectionChangeCommitted);
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        List<string> list = new List<string> { "a", "b", "c" };
        comboBox1.DataSource = list;
        comboBox1.SelectedIndex = 0;
    }
    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        MessageBox.Show(comboBox1.SelectedValue.ToString());
    }
    private void button1_Click(object sender, EventArgs e)
    {
        comboBox1.SelectedIndex = 1;

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-14
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    相关资源
    最近更新 更多