Datagridview row selecting font colors using C#

BgnerNprg207 286 Reputation points
2024-06-22T12:43:23.6633333+00:00

Good day! I have a DataGridView, Inside the DataGridView they have 2 types font text color that is color black and color red. Please see the image below.

sample

Now I want is! If I double click the row where the font text color black means read only. But! if I double click the row where the font text is color red it's show a message.

I have a code here but it's not work for me.

1st attempt code:

private void dataGridView2_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

            foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                if (row.DefaultCellStyle.ForeColor == Color.Black)
                {
                  //
                }
                else if (row.DefaultCellStyle.ForeColor != Color.Black)
                {
                    MessageBox.Show("red");
                }
                break;
            }
}

2nd attempt code:

private void dataGridView2_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                var now = DateTime.Now;
                var cellDate = DateTime.Parse(row.Cells[12].Value.ToString());
                if (now < cellDate)
                {
                    //row.DefaultCellStyle.BackColor = Color.Red;
                    MessageBox.Show("color red");
                }
               
            }
}

Both of this attempt 1and 2 is not work for me.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,574 questions
{count} votes

Accepted answer
  1. KOZ6.0 6,300 Reputation points
    2024-06-23T04:48:52.5833333+00:00

    The range in which the CellContentDoubleClock event fires is very small.

    In the image below, that range is the area surrounded by the blue line. If you want to target the entire cell, use the CellDoubleClick event.

    enter image description here

    row.DefaultCellStyle.ForeColor may be either Color.Empty, Color.Red or Color.Blue. row.InheritedStyle.ForeColor may be either SystemColors.ControlText, Color.Red or Color.Blue.

    Does not match Color.Black.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. BgnerNprg207 286 Reputation points
    2024-06-23T04:42:02.0066667+00:00

    Good day KOZ6.0, I already fix this problem. I use DBConnection to check the old date in my DataGridView.

    MySqlCommand cmd = new MySqlCommand("SELECT * FROM MyDb WHERE schedule < NOW()", DBConnection.con);
                    MySqlDataReader reader = cmd.ExecuteReader();
    
    
    
    0 comments No comments