[基础控件:combox绑定List<T>集合,始终绑定出item.toString]
combox的dataSource可以绑定dataTable,也可以绑定list,或者arrayList等,也可以直接创建1个BindingSource对象,今天写了1个利用泛型,从枚举中读取成1个下拉选择的数据源的方法,中间没有给list中的对象get方法,然后F5运行的时候,combox始终显示1个list.item[i].toString的值的列表,这肯定不是我想要的结果,中间百度了很多,都没有结果,后来试出来的,在list中的对象的要访问的属性上加上get方法就好了,也不知道为什么,因为如果我不写get和set的话,编译器是会自动给我加上的,但是这里为什么没有用,疑问!
解决办法就是在对象上加上get访问器。
读取枚举到列表的工具方法为:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace WindowsFormsApplication7 7 { 8 class BindComboxEnumType<T> 9 { 10 //奇葩问题: 11 //必须提供get访问器,否则combox会显示list中item[i].toString() 12 public string Name { get; private set; } 13 public T Type { get; private set; } 14 15 private static readonly List<BindComboxEnumType<T>> bindTyps; 16 public static List<BindComboxEnumType<T>> BindTyps { 17 get { 18 return bindTyps; 19 } 20 } 21 22 static BindComboxEnumType(){ 23 bindTyps = new List<BindComboxEnumType<T>>(); 24 25 foreach (var name in Enum.GetNames(typeof(T))) 26 { 27 bindTyps.Add(new BindComboxEnumType<T>() { 28 Name = name, 29 Type = (T)Enum.Parse(typeof(T), name) 30 }); 31 } 32 } 33 34 } 35 }
调用为:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.Collections; 10 11 namespace WindowsFormsApplication7 12 { 13 public partial class Form1 : Form 14 { 15 public Form1() 16 { 17 InitializeComponent(); 18 } 19 20 private void Form1_Load(object sender, EventArgs e) 21 { 22 this.comboBox1.DataSource = BindComboxEnumType<State>.BindTyps; 23 this.comboBox1.DisplayMember = "Name"; 24 this.comboBox1.ValueMember = "Type"; 25 26 this.comboBox1.SelectedIndex = 0; 27 } 28 } 29 }
<完>
浙公网安备 33010602011771号