多年不写 Winform 了,忽然要作一个 winform 项目,各类不顺手,各类百度。async
DataGridView 数据绑定的一些细节问题,记录备查。code
BindingList<EmployeeVO> dataSource; private async void FrmEmployeeInfo_Load(object sender, System.EventArgs e) { List<EmployeeVO> employees = await employeeApi.GetList(); dataSource = new BindingList<EmployeeVO>(employees); dgvEmployees.DataSource = dataSource; }
绑定数据后,添加删除行,直接对 dataSource
进行 Add
和 Remove
操做,界面会自动更新。更新数据,若是直接对 dataSource
中的元素属性进行修改,界面不会刷新,须要点击修改的元素,才会刷新。要当即刷新,能够用一个新的实例替换掉 dataSource
被修改的实例。orm
dgvEmployees.AutoGenerateColumns = false;
若是实例中有些列不想显示,就须要阻止自动建立列。string
另外,当有 Link 等列时,若是设置此属性,Link 列的 Index
会被排在 TextBox
列以前,致使 ColumnIndex
错乱。it
private void dgvEmployees_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (dgvEmployees.Columns[e.ColumnIndex].HeaderText == "技能") { List<SkillVO> skills = e.Value as List<SkillVO>; e.Value = string.Join(", ", skills.Select(s => s.Name)); } }