【C#】DataGridView 資料繫結的一些細節
阿新 • • 發佈:2020-08-16
多年不寫 Winform 了,突然要做一個 winform 專案,各種不順手,各種百度。
DataGridView 資料繫結的一些細節問題,記錄備查。
資料繫結
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
被修改的例項。
阻止自動建立列
dgvEmployees.AutoGenerateColumns = false;
如果例項中有些列不想顯示,就需要阻止自動建立列。
另外,當有 Link 等列時,如果設定此屬性,Link 列的 Index
會被排在 TextBox
列之前,導致 ColumnIndex
錯亂。
自定義資料格式
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)); } }