【问题标题】:Behavior of Combobox.SelectedIndexChangedCombobox.SelectedIndexChanged 的​​行为
【发布时间】:2013-04-05 19:42:22
【问题描述】:

请看下面的代码。当应用程序启动时 SelectedIndexChanged 被调用并且 x 是“示例”类型。但是当应用程序运行并且您选择不同的东西时,SelectedIndexChanged 会产生一个结果 x 类型的浮点数。为什么这会产生不同的结果?

{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var example = new List<Example>();

            example.Add(new Example("A", 100f));
            example.Add(new Example("B", 200f));
            example.Add(new Example("C", 400f));

            this.comboBox1.DataSource = example;

            this.comboBox1.DisplayMember = "Description";
            this.comboBox1.ValueMember = "Value";
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var x = this.comboBox1.SelectedValue;
        }
    }

    public class Example
    {
        public Example(string desc, float val)
        {
            this.Description = desc;
            this.Value = val;
        }

        public string Description { get; set; }
        public float Value { get; set; }
    }
}

【问题讨论】:

  • 在大多数情况下,您可能想回复SelectionChangeCommitted,即当用户交互实际参与组合框时。

标签: c# winforms events combobox


【解决方案1】:

在发布我的问题之前,我尝试了不同的方法并找到了答案:

SelectedIndexChanged 在设置 DataSource 时触发。在这个特定时刻,程序不知道哪一列是 DisplayMember 和 ValueMember,并返回类型 Example。

要获得预期的结果,您首先必须告诉控件将什么用作 DisplayMember 和 ValueMember 以及 在设置数据源之后

this.comboBox1.DisplayMember = "Description";
this.comboBox1.ValueMember = "Value";
this.comboBox1.DataSource = example;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 2020-04-08
    • 2011-08-31
    相关资源
    最近更新 更多