Click here to Skip to main content
15,887,980 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone,

I have a form with a DataGridView.
Using SQL I want to select all content from a table, in my case is
"SELECT * FROM dbo.ripRiparazioni;", and highlight with colour yellow only the rows that have a date of three days ago.

This is my code, at the moment:

C#
string SQLquery = "SELECT * FROM dbo.ripRiparazioni";

            SqlDataAdapter da = new SqlDataAdapter(SQLquery, connessione);

            DataSet ds = new DataSet();

            da.Fill(ds);

            dataGridView1.DataSource = ds.Tables[0];


How can I do?
Posted

1 solution

First, the colour setting isn't in a vastly obvious place:
C#
myRow.DefaultCellStyle.BackColor = Color.Yellow;

Then, handle the DGV RowPrePaint event:
C#
private void MyView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {
    DataGridView dgv = sender as DataGridView;
    if (dgv != null)
        {
        DataGridViewRow myRow = dataGridView1.Rows[e.RowIndex];
        DateTime date = (DateTime)myRow.Cells["InsertDate"].Value;
        if (date.Date >= DateTime.Now.AddDays(-3).Date)
            {
            myRow.DefaultCellStyle.BackColor = Color.Yellow;
            }
        }
    }
 
Share this answer
 
Comments
Pikoh 25-Nov-14 10:42am    
I'm curious. Why RowPrePaint and not CellFormatting? What are the avantages or differeces between them?
OriginalGriff 25-Nov-14 11:00am    
Efficiency. CellFormatting is called for each cell before it is painted (and that can be a heck of a lot of events) - RowPrePaint is called once per row just before it is painted.
Pikoh 25-Nov-14 11:04am    
Thank you very much. Now i know i've done it the wrong way for years :)
OriginalGriff 25-Nov-14 11:08am    
Doesn't surprise me - the framework is so big it's easy to miss things: I do it all the time!
nicola_melc 25-Nov-14 11:24am    
The code it's right, but I' ve an error.

When it finish the datagridview's rows, it continue to control and I have the error:

object reference not set to an instance of object

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900