[.net] C# DataGridView DataSet and table row color

Started by
4 comments, last by Arild Fines 17 years, 5 months ago
C# gurus, Is there a way to set/save the row color inside the DataSet table? More explanation: I use DataSet to set up a data table and bind it to DataGridView. I want to set specific ForeColors for certain rows in the table based on a row cell value. This is the way I know how: DataGridViewRow row; row = dataGridView1.Rows; row.DefaultCellstyle.ForeColor = Color.Red; This doesn't seem to be the best way, because the color setting only applies to DataGridView, doesn't get stored inside the DataSet table. So if I do something like filtering the rows and re-binding the data table, like this: DataView dv = new DataView(tbl.Tables[0]); dv.RowFilter = "CODE=1"; dataGridView1.DataSource = dv; ...then it's necessary to re-apply the row colors because it's not done automatically.
Advertisement
Here's a sample from one of my apps.

for (int r = 0; r < noOfRows; r++){   for (int c = 0; c < noOfColumns; c++)   {      if (newBytes[index] != oldBytes[index])      {         dataGridView1.Rows[r].Cells[c].style.ForeColor = Color.Red;      }      else      {         dataGridView1.Rows[r].Cells[c].style.ForeColor = Color.Black;      }   }}


EDIT: This only works after the cells have been added to the DataGridView.
Thanks CodeReaver.

This is similar to how I did it also, via the DataGridView cell stle. But, I am really interested to know if color can be applied to the row elements in the DataSet table before the table is added to DataGridView.

May be it's not possible because I don't see any methods in DataSet for setting cell colors. Thanks.
Why on earth would DataSet contain anything that had to do with how the data is presented to the user? Such a thing is not a concern for a DataSet whose sole purpose in life is managing a set of... data.

No, you'll have to implement this mostly for yourself, especially since the behavior is non-trivial behavior (the colors are context sensitive).

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

I'd just like to second Washu's incredulity. A data set (or a DataSet) is for data, not presentation.

The way CodeReaver and you are doing it now is fine.
Best way to do conditional formatting of the cells in a DataGridView is to handle the .CellFormatting event.
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]

This topic is closed to new replies.

Advertisement