user47589
user47589

Reputation:

Datagridview row formatting based on data

I have a DataGridView bound to a BindingSource. Each row has three fields: Name, StartDate, EndDate. Elsewhere on my form, I have a DateTimePicker control.

When the DateTimePicker's date is between a row's start and end dates, I want to highlight that row. But I cannot figure out how to do this. Can anyone give me a starting point?

Upvotes: 2

Views: 10333

Answers (2)

Agustin Osorio
Agustin Osorio

Reputation: 51

If you need the complete row to be highlighted then you may want to use the DefaultCellStyle property for each Row, either in a ForEach loop or you can use the CellFormatting Event as seen below:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Error")
    {
        if (e.Value != null && e.Value.ToString() == "1")
        {
             dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
        }
    }
}

Upvotes: 5

John
John

Reputation: 16007

Do you want to highlight all of the rows that meet the condition?

You can go through row by row to see which rows satisfy the condition each time the DTP value changes.

Then, for each cell in these rows, change DataGridViewCell.Style however you want to highlight the rows. For each cell that is in a row that doesn't satisfy the constraint, set DataGridViewCell.Style to the default.

Upvotes: 1

Related Questions