今天给一个ComboBox绑定数据源后,在调用SelectedValue给其赋值的时候(值是有的),发现该ComboBox的SelectedValue始终为null:
this.cboboxJob.DataSource = ltJobsType; //ltJobsType是List<T>泛型集合
this.cboboxJob.DisplayMember = "DNAME"; //DNAME为string类型
this.cboboxJob.ValueMember = "ID"; //ID为int类型
给其赋值:
this.cboboxJob.SelectedValue = "12"; //注意此处,12是字符串类型的,这个12是另一张表中存储的,取出来的类型是string类型
发现这句话执行完成之后,this.cboboxJob.SelectedValue一直为null
经过摸索,发现是类型不匹配造成的,因为绑定的ValueMember是int类型,而给SelectedValue赋值的却是string类型,故一直赋不上值。
解决方法:
将this.cboboxJob.SelectedValue = "12"; 中的"12"转换为int类型即可。
个人愚见,如有错误,欢迎指正,不胜感激!!!