【问题标题】:How to edit a cell value while databinding a datagridview?如何在数据绑定数据网格视图时编辑单元格值?
【发布时间】:2011-03-23 09:47:35
【问题描述】:
我有一个对象列表(类型 A),它们充当我的 datagridview 的数据源。 A 类型的属性是 B 类型的对象列表。
我想在单元格中显示类型 B 的列表。我想使用对象 B 的 Description 属性来执行此操作。datagridview 中显示的(对象 B)描述以逗号分隔。
我必须挂钩哪个事件才能编辑单元格值?我不想向我的对象添加属性,因为我将修改我的对象以进行 UI 表示,而这我不想要。
【问题讨论】:
标签:
c#
winforms
datagridview
【解决方案1】:
我终于找到了一些东西。我不知道这是否是正确的方法,但它现在对我有用。这是我所做的:
1) 我已将 datagridview 的属性 VirtualMode 设置为 true。
2) 我处理CellValueNeeded 事件。在此事件处理程序中,我检查列索引并设置值:
private void myDataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
if (e.ColumnIndex == 3)
{
// _appointments is a member variable which is the datasource of the grid
Appointment appointment = _appointments[e.RowIndex];
IList<DisciplineType> disciplines = appointment.GetDisciplines();
for (int i = 0; i < disciplines.Count; i++)
{
if (i > 0)
e.Value += ", " + disciplines[i].Description;
else
e.Value += disciplines[i].Description;
}
}
}
希望这对其他人也有帮助。或者如果您有更好的解决方案,请告诉我。