I have a DataGridView. I set its .DataSource prop to be an BindingList of my own objects: a BindingList<IChessItem>
I then created some columns for it..
DataGridViewTextBoxColumn descColumn = new DataGridViewTextBoxColumn();
descColumn.DataPropertyName = "Description";
descColumn.HeaderText = "Description";
descColumn.Width = 300;
DataGridViewTextBoxColumn gameIDColumn = new DataGridViewTextBoxColumn();
gameIDColumn.DataPropertyName = "GameID";
gameIDColumn.HeaderText = "Game ID";
gameIDColumn.Width = 60;
dataGrid.Columns.Add(descColumn);
dataGrid.Columns.Add(gameIDColumn);
My question is.. I want to color one of the columns GREEN based upon data in another field of my BindingList). How can I do this?
I don't really have to show this field, I just want to act upon the data in it..
in my case, one of the fields of IChessItem shows whether the record is new, and I want to color the other fields in the datagridview to reflect that.
You can use the 'CellFormatting' event of the DataGridView. The DataGridViewCellFormattingEventArgs contains indexes of the row and the column of the current cell as it is being bound. I hope my code example makes some sense to you:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// Compare the column to the column you want to format
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "ColumnName")
{
//get the IChessitem you are currently binding, using the index of the current row to access the datasource
IChessItem item = sourceList[e.RowIndex];
//check the condition
if (item == condition)
{
e.CellStyle.BackColor = Color.Green;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With