How to access the "real" object behind cells in DataRow
I wanna associate a custom object to each cell in a DataTable
's DataRow
so that, on the events I get from the DataGridView, I can customize coloring and other behavior. So, when I add a new row, I do the following:
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);
On the DataGridView's CellFormatting 开发者_Go百科event, I want to get my ClsCelula object to read it's properties, like below:
Object oCelula = dtItens.Rows[e.RowIndex][e.ColumnIndex];
if (oCelula != null)
{
if (oCelula is ClsCelula)
{
ClsCelula oValorCelula = (ClsCelula)oCelula;
e.CellStyle.BackColor = oValorCelula.Cor;
}
}
However, this doesn't work, since probably the code is calling ToString()
when I read the Row/Column index, so oCelula is always a System.String
. Is there any way around this? How can I access the "real" object?
Since you are working from an object model, there seems to be no need to use DataTable
here all - just set the DataSource
to a List<T>
(or better: BindingList<T>
) and away you go! DataGridView
is perfectly happy binding to objects, and the underlying object is just .DataBoundItem
on each row.
Note - for two-way data-binding (i.e. If you want the grid to update when you edit an object directly through code) you might want to use BindingList<T>
and implement INotifyPropertyChanged
- but this isn't necessary if you just want to display a list and edit items via the grid.
Several options here:
- create
DataTable
from your ownDataColumn
objects, and specify the each column object type asClsCelula
. You'll have problems formatting it for the grid, in this case. - create second invisible i.e. shadow column for each object created, then in it put the index of the object in some
Dictionary<int, ClsCelula>
or such, where index would be some kind of autoincrement number you will have to create and maintain. - do what Marc says in the comment. That is the best thing you can do here.
I found such thing in my code: dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value
. You might have to cast that to a particular type.
Old question, but anyway:
DataGridRecord obj = (DataGridRecord)Rows[args.RowIndex].DataBoundItem;
精彩评论