I have a DataGridView that uses databinding, with manually created columns, and this works fine.
However I want the rows’ BackColor to be databound as well, and so far my attempts have hit errors.
This is my latest attempt:
dataGridFileTransfer.RowHeadersVisible = false;
dataGridFileTransfer.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridFileTransfer.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridFileTransfer.MultiSelect = false;
dataGridFileTransfer.ReadOnly = true;
var files = GetReceivedFiles(false).Union(FileDetails.Select(FileStatus.FailedVerification)).ToList();
dataGridFileTransfer.AutoGenerateColumns = false;
string[] displayHeaders = new string[] { COL_NAME, COL_TYPE, COL_CREATED, COL_SIZE, COL_STATUS };
string[] displayProps = new string[] { "Filename", "FileTypeDisplayName", "Created", "Size", "FileStatus" };
for (int i = 0; i < displayHeaders.Length; i++)
{
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = displayHeaders[i];
col.DataPropertyName = displayProps[i];
if (displayHeaders[i] == COL_CREATED)
col.DefaultCellStyle.Format = Constants.DDMMYYYHHMMSS;
dataGridFileTransfer.Columns.Add(col);
}
Binding bi = new Binding("DefaultCellStyle.BackColor", files, "DisplayColor");
dataGridFileTransfer.DataBindings.Add(bi);
dataGridFileTransfer.DataSource = files;
Which is generating an ArguementException:
“Cannot bind to the property
“DefaultCellStyle.BackColor’ on the
target control. Parameter name:
PropertyName”
Is it the value of PropertyName that is wrong, or should I binding to an object other than the DataGridView? (i.e. a column?)
Or is the problem that PropertyName cannot be in the form X.Y? I thought I had seen/used this syntax before, but maybe it only works for DataMember?
Any help is much appreciated
I think the problem is
files.DisplayColor.filesis a collection an has no propertyDisplayColorbut each item of the collection has. So you are trying to bind a not existing property. Further binding collectionDataGridView.DataBindingsallows you to data bind properties of the control, not of its rows. There is only oneDataGridView.DefaultCellStyle.BackColorfor all rows. So I believe you end up needing to bind theDefaultCellStyleof each row to the coresponding item fromfilesand I am not sure if this is possible. It might be that theDataGridViewcreates and deletes rows as required – for example if you perform filtering – and this will destroy the data binding, too.So, I am not sure if row coloring can be done with data binding, but I personaly doubt it. This would require some really smart logic recognicing ‘bind the property
DisplayColorof the object data bound to this row to the propertyDefaultCellStyle.BackColorof this row.’You could surly implement such an smart data binding. While it would be a great thing, it will be quite complex, too. As a simple solution you could just use the
RowPrepaintevent to set the correct color for the row.