1

我想将自定义对象关联到 a 中的每个单元格,DataTable以便DataRow在从 DataGridView 获得的事件上,我可以自定义颜色和其他行为。因此,当我添加新行时,我会执行以下操作:

  DataRow oRow = dtItens.NewRow();
  oRow["CodFamilia"] = new ClsCelula(TipoCelula.tcMostrar, "", Color.White);
  oRow["Familia"] = new ClsCelula(TipoCelula.tcMostrar, "", Color.White);
  oRow["Item"] = new ClsCelula(TipoCelula.tcMostrar, "", Color.White);
  oRow["Descricao"] = new ClsCelula(TipoCelula.tcMostrar, "", Color.White);
  oRow["Referencia"] = new ClsCelula(TipoCelula.tcMostrar, "Saldo Inicial", Color.Aqua);
  dtItens.Rows.Add(oRow);

在 DataGridView 的 CellFormatting 事件中,我想让我的 ClsCelula 对象读取它的属性,如下所示:

Object oCelula = dtItens.Rows[e.RowIndex][e.ColumnIndex];
if (oCelula != null)
{
  if (oCelula is ClsCelula)
  {
    ClsCelula oValorCelula = (ClsCelula)oCelula;
    e.CellStyle.BackColor = oValorCelula.Cor;
  }
}

但是,这不起作用,因为ToString()当我读取行/列索引时,代码可能正在调用,所以 oCelula 始终是System.String. 有没有办法解决?如何访问“真实”对象?

4

4 回答 4

2

由于您正在使用对象模型,因此似乎没有必要在DataTable这里全部使用- 只需将 设置DataSource为 a List<T>(或更好:)BindingList<T>然后就可以了!DataGridView非常高兴地绑定到对象,并且底层对象就.DataBoundItem在每一行上。

注意 - 对于双向数据绑定(即,如果您希望在直接通过代码编辑对象时更新网格),您可能想要使用BindingList<T> 实现INotifyPropertyChanged- 但如果您只想显示列表和通过网格编辑项目。

于 2011-02-13T23:00:52.650 回答
1

这里有几个选项:

  • DataTable从您自己的对象创建DataColumn,并将每个列对象类型指定为ClsCelula. 在这种情况下,您将无法为网格格式化它。
  • 为创建的每个对象创建第二个不可见的即阴影列,然后在其中放置对象的索引Dictionary<int, ClsCelula>,其中索引将是您必须创建和维护的某种自动增量数字。
  • 做马克在评论中所说的。这是你可以在这里做的最好的事情。
于 2011-02-13T22:17:35.400 回答
0

我在我的代码中发现了这样的东西:dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value. 您可能必须将其转换为特定类型。

于 2011-02-13T22:09:03.797 回答
0

老问题,但无论如何:

DataGridRecord obj = (DataGridRecord)Rows[args.RowIndex].DataBoundItem;
于 2018-03-23T08:55:34.527 回答