【C#】comboBox控件的DisplayMember和ValueMember


combox的这个功能有时候用来保存数据内容和对应的id,
combox的这两个代码只有在绑定数据源的时候才可以用。
请看代码演示:

  Department department = new Department();
IList<DepartmentInfo> depts = department.GetDepartments();
this.cmbDepartment.DisplayMember = "Department_Name";
this.cmbDepartment.ValueMember = "Department_Id";
this.cmbDepartment.DataSource = depts.ToList();

其他信息在下面的注明中,这里将展示的信息设置为Department_Name,保存的value设置为Department_Id,然后用datasource绑定数据源,即从数据库中返回的查询结果。
这样设置有利于取选中的项的value值,是一种很常见的做法。
注明:
DepartmentInfo是一个部门类,用来保存部门的信息,详细如下public class DepartmentInfo
{
public DepartmentInfo() { }

    public DepartmentInfo(string departmentId, string departmentName)
{
this.Department_Id = departmentId;
this.Department_Name = departmentName;
}

[Column(Name = "Department_Id", IsPrimaryKey = true, DbType = "varchar(3)")]
public string Department_Id { get; set; }

[Column(Name = "Department_Name", DbType = "varchar(50)")]
public string Department_Name { get; set; }
}epartment是一个操作类类,用来保存部门的信息的操作,详细如下:
 public class Department : IDepartment
{
public IList<DepartmentInfo> GetDepartments()
{
StudentMgmtDataContext db = new StudentMgmtDataContext();
var departments = from d in db.Departments
select d;

return departments.ToList();
}
}

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号