Winform动态增加ComboBox后SelectedValue无效的问题
2017-06-16 14:35
211 查看
窗体上动态创建ComboBox控件,并且打算初始化时自动选定值为"2“的项,代码如下:
发现执行后SelectedValue还是为null,创建的ComboBox无法选定2这项,搞了半天,终于在一篇文章里找到原因。
原因是动态的ComboBox要在控件创建的时候,才能确定它的父窗体parent,如果没有parent那么SelectedValue则无效。。。不知道是不是BUG
解决方案是在SelectedValue前,记住一定要在这之前,不能之后,加入所属父窗体的设置即可:
参考:
http://blog.163.com/prince.king_521/blog/static/106891204201021735844711/
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/
相关文章推荐
- jquery中动态增加select,事件无效问题
- C# winform程序中动态菜单的问题
- [问题-unfinished],怎样使动态改变的js里的document.write任意时间都可以显示在页面上, 问题是不在appendChild前面加一个alert() , append上去的js中的document.write语句通通无效
- 动态执行Sql语句与临时表的问题(对象名无效)
- WINFORM中两个 ComboBox 控件绑定同一个数据源的问题
- # winform comboBox动态下拉列表,comboBox动态绑定数据库里的数据
- 再谈如何实现动态增加(选取)报表字段的问题
- Extjs中的combobox的动态加载问题
- WinForm中线程问题:线程间操作无效: 从不是创建控件“...”的线程访问它
- WinForm给ComboBox增加Value
- Asp.net开发心得点滴[动态加载的用户控件使用事件委托,交给页面处理的事件无效问题]
- .Net之Winform桌面应用程序中Combobox三级下拉菜单连动问题的解决方案
- c# winForm TableLayoutPanel学习 合并行的布局及动态增加删除内部控件
- c# winform comboBox动态绑定数据
- Javascript动态为Select控件添加项并设置控件值无效的问题
- 动态执行Sql语句与临时表的问题(对象名无效)
- 再谈如何实现动态增加(选取)报表字段的问题
- c# winForm TableLayoutPanel学习 合并行的布局及动态增加删除内部控件
- 解决在VS(winform)程序中无法在调试时修改代码的问题(也就是“编辑并继续”功能无效)
- 利用JavaScript动态增加的文本输入框在后台无法取值问题的解决