窗体上动态创建ComboBox控件,并且打算初始化时自动选定值为"2“的项,代码如下:
ComboBox comboBoxCarPlateColor = new ComboBox();
var listCarPlateColor = new List<KeyValuePair<string, string>>();
listCarPlateColor.Add(new KeyValuePair<string, string>("1", "蓝色"));
listCarPlateColor.Add(new KeyValuePair<string, string>("2", "黄色"));
listCarPlateColor.Add(new KeyValuePair<string, string>("3", "黑色"));
listCarPlateColor.Add(new KeyValuePair<string, string>("4", "白色"));
listCarPlateColor.Add(new KeyValuePair<string, string>("5", "其它"));
comboBoxCarPlateColor.DataSource = listCarPlateColor;
comboBoxCarPlateColor.ValueMember = "key";
comboBoxCarPlateColor.DisplayMember = "value";
comboBoxCarPlateColor.SelectedValue = "2";
this.Controls.Add(comboBoxCarPlateColor);
发现执行后SelectedValue还是为null,创建的ComboBox无法选定2这项,搞了半天,终于在一篇文章里找到原因。
原因是动态的ComboBox要在控件创建的时候,才能确定它的父窗体parent,如果没有parent那么SelectedValue则无效。。。不知道是不是BUG
解决方案是在SelectedValue前,记住一定要在这之前,不能之后,加入所属父窗体的设置即可:
ComboBox comboBoxCarPlateColor = new ComboBox();
var listCarPlateColor = new List<KeyValuePair<string, string>>();
listCarPlateColor.Add(new KeyValuePair<string, string>("1", "蓝色"));
listCarPlateColor.Add(new KeyValuePair<string, string>("2", "黄色"));
listCarPlateColor.Add(new KeyValuePair<string, string>("3", "黑色"));
listCarPlateColor.Add(new KeyValuePair<string, string>("4", "白色"));
listCarPlateColor.Add(new KeyValuePair<string, string>("5", "其它"));
comboBoxCarPlateColor.DataSource = listCarPlateColor;
comboBoxCarPlateColor.ValueMember = "key";
comboBoxCarPlateColor.DisplayMember = "value";
comboBoxCarPlateColor.Parent = this;//加入这一句
comboBoxCarPlateColor.SelectedValue = "2";
this.Controls.Add(comboBoxCarPlateColor);
参考:
http://blog.163.com/prince.king_521/blog/static/106891204201021735844711/