如何在dataGridView C#中设置行颜色?

时间:2016-12-21 08:16:26

标签: c# datagridview

如果状态="不完整"然后行颜色应为红色。我怎样才能做到这一点? 状态字段位于第8列。DataGridView

String query = "select * from bug order by id desc;";
String Status = null;                     
DataTable dt = connection.retrieve(query);
for (int i = 0; i < dataGridViewDashboard.Rows.Count; i++)
{
    Status = dataGridViewDashboard.Rows[i].Cells[8].Value.ToString();
    if (Status == "Incomplete")
    {
        dataGridViewDashboard.Rows[i].DefaultCellStyle.BackColor = Color.Red;
    }
    else
    {
        dataGridViewDashboard.Rows[i].DefaultCellStyle.BackColor = Color.Green;
    }
}

2 个答案:

答案 0 :(得分:0)

您必须控制是否为新行。

    String query = "select * from bug order by id desc;";
    String Status = null;                     
    DataTable dt = connection.retrieve(query);
    for (int i = 0; i < dataGridViewDashboard.Rows.Count; i++)
    {
       if (dataGridViewDashboard.Rows[i].IsNewRow)
                continue;
        Status = dataGridViewDashboard.Rows[i].Cells[8].Value.ToString();
        if (Status == "Incomplete")
        {
            dataGridViewDashboard.Rows[i].DefaultCellStyle.BackColor = Color.Red;
        }
        else
        {
            dataGridViewDashboard.Rows[i].DefaultCellStyle.BackColor = Color.Green;
        }
    }

答案 1 :(得分:0)

您必须订阅DataGridView的PrePaint事件,并且可以轻松设置行的颜色。

  private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e){
if (your control here) 
{
    dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
}}