C# Combobox.SelectedIndex的行为已更改
请看下面的代码。当应用程序启动时,将调用SelectedIndexChanged,x的类型为“Example”。但是,当应用程序运行时,您选择了不同的内容SelectedIndexChanged将生成一个x类型的浮点结果。为什么这会产生不同的结果C# Combobox.SelectedIndex的行为已更改,c#,winforms,events,combobox,C#,Winforms,Events,Combobox,请看下面的代码。当应用程序启动时,将调用SelectedIndexChanged,x的类型为“Example”。但是,当应用程序运行时,您选择了不同的内容SelectedIndexChanged将生成一个x类型的浮点结果。为什么这会产生不同的结果 { public partial class Form1 : Form { public Form1() { InitializeComponent();
{
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; }
}
}
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
var示例=新列表();
示例。添加(新示例(“A”,100f));
添加(新示例(“B”,200f));
示例。添加(新示例(“C”,400f));
this.comboBox1.DataSource=示例;
this.comboBox1.DisplayMember=“Description”;
this.comboBox1.ValueMember=“Value”;
}
私有无效组合框1\u SelectedIndexChanged(对象发送方,事件参数e)
{
var x=this.comboBox1.SelectedValue;
}
}
公开课范例
{
公共示例(字符串描述、浮点值)
{
此.Description=desc;
这个值=val;
}
公共字符串说明{get;set;}
公共浮点值{get;set;}
}
}
在发布我的问题之前,我尝试了不同的方法并找到了答案:
SelectedIndexChanged在设置数据源时触发。在此特定时刻,程序不知道哪个列是DisplayMember和ValueMember,并返回类型示例
要获得预期的结果,首先必须告诉控件使用什么作为DisplayMember和ValueMember,并在设置数据源的之后告诉控件使用什么
this.comboBox1.DisplayMember = "Description";
this.comboBox1.ValueMember = "Value";
this.comboBox1.DataSource = example;
在发布我的问题之前,我尝试了不同的方法并找到了答案: SelectedIndexChanged在设置数据源时触发。在此特定时刻,程序不知道哪个列是DisplayMember和ValueMember,并返回类型示例 要获得预期的结果,首先必须告诉控件使用什么作为DisplayMember和ValueMember,并在设置数据源的之后告诉控件使用什么
this.comboBox1.DisplayMember = "Description";
this.comboBox1.ValueMember = "Value";
this.comboBox1.DataSource = example;
在大多数情况下,您可能希望响应
SelectionChangeCommitted
,即当用户交互实际使用组合框时。在大多数情况下,您可能希望响应SelectionChangeCommitted
,即当用户交互实际使用组合框时。