views:

35

answers:

2

Hello everyone,

I have the following problem

In my aplication I doing some calculations and after it put them into DataTable object (6 columns, data in the latest one is most important). To view the results I put them into DataGridView object and there is my problem. Depending on the data contained in the last column I want to mark the cells on the appropriate colors. And I don't know if I should do this on the DataGridView object because this is user interfaces? Where I can do this? DataTable object doesn't have a style properties?

Thanks a lot...

A: 

You can use the CellPainting event of the DataGridView to format your cells based on their content.

e.g. `

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
        {

            switch (dataGridView1.Columns[e.ColumnIndex].DataPropertyName)
            {
                case "Description":
                    {
                        break;
                    }
                case "NormalRoom":
                    {
                        break;
                    }
                case "Colour1":
                case "Colour2":
                    {
                        Color co = Color.White;
                        if (e.Value != null && e.Value != DBNull.Value)
                        {
                            co = string2Color((string)e.Value);
                        }
                        e.CellStyle.BackColor = Color.White;
                        e.CellStyle.ForeColor = Color.Black;

etc.`

FixerMark
Karol's solution would work but may be slow if the dataset is large. Also you would need to ensure it ran each time the data changed. My method has the advantage that it is automatic and efficient as it only needs to handle the data actually visible on the screen.
FixerMark
A: 

I've done simething like this:

 public void setABCColor(DataGridView DGV)
    {
        for (int i = 0; i < DGV.Rows.Count; i++)
        {
            if ((string)DGV.Rows[i].Cells[6].Value == "A")
            {
                DGV.Rows[i].Cells[6].Style.BackColor = Color.Green;
            }
            else if ((string)DGV.Rows[i].Cells[6].Value == "B")
            {
                DGV.Rows[i].Cells[6].Style.BackColor = Color.Blue;
            }
            else
            {
                DGV.Rows[i].Cells[6].Style.BackColor = Color.Red;
            }
        }
    }

Is this acceptable? Is this not change the assumption of the MVC design pattern?

Karol