首先我的代码.我有一节课:
class Person { public int Id { set; get; } public string Name { set; get; } public Person(int i,string n) {Id = i; Name = n;} }
和一个ComboBox对象:
this.comboBox_Persons = new System.Windows.Forms.ComboBox();
在我的代码中的某个地方:
List<Person> persons = new List<Person>() { new Person(5,"John"),new Person(8,"Mike") }; comboBox_Persons.Items.Clear(); comboBox_Persons.DisplayMember = "Name"; comboBox_Persons.ValueMember = "Id"; comboBox_Persons.DataSource = persons;
以及静态成员和事件处理程序:
public static string test = ""; void comboBox_PersonsSelectedIndexChanged(object sender,EventArgs e) { test = test + "1"; string id = (string) comboBox_Persons.SelectedValue; }
int id = (int) comboBox_Persons.SelectedValue;
我花了一些时间才意识到我的问题就在这一行.
为什么comboBox_Persons.DataSource被填充时没有抛出异常?
当我的表单准备就绪时,comboBox_Persons包含两个项目,它应该显示“John”和“Mike”,但事实并非如此.组合框显示类Person的类型名称(带名称空间)两次.而且,静态字段’test’的值是“11”,这意味着已经调用了事件处理程序.但下一行(使用强制转换为字符串)应抛出异常,但事实并非如此.为什么?接下来,当我单击组合框并更改所选值时,将调用事件处理程序并抛出异常(告知它不能转换为字符串).
那么,为什么在设置DataSource时,comboBox不会抛出任何异常?
为什么comboBox显示类型名称而不是定义属性’Name’?
我想知道为什么这个控件的行为方式如此,我在.NET文档和Internet上找不到任何答案.
当我将错误的行更改为正确的版本时,一切正常.
解决方法
我在google上搜索comboBox源代码,看看它是如何实现的,以及为什么异常被埋没了,我发现了这个:
有趣的是,如果你在SelectedIndexChanged事件中添加一行来抛出异常,那么应用程序不会崩溃!
private void comboBox_persons_SelectedIndexChanged(object sender,EventArgs e) { test = test + "1"; string id = (string)comboBox_Persons.SelectedValue; throw new ApplicationException("Test"); }
显然,这是64位计算机的问题,并且有一个针对此问题的修补程序.正如本文所述,Form_Load事件中的异常代码不会破坏应用程序!与comboBox SelectedIndexChanged事件类似.
我无法测试此修补程序,因为我的计算机上没有安装Win 7 SP1.但是,根据博客中的评论,此修补程序实际上并未修复所有问题,而异常被埋在64位计算机中.
我希望这些信息对你有用!