Pregunta

Tengo un DataGridView compuesto por varias filas y columnas. Quiero recorrer cada fila y comprobar el contenido de una columna específica. Si esa columna contiene la palabra "NO", quiero cambiar el color de primer plano de toda la fila a rojo. He aquí un intento de algo de código hasta el momento, pero ciertamente no está funcionando, comenzando a preguntarse si necesito iterar sobre cada célula?

CÓDIGO:

foreach (DataGridViewRow dgvr in dataGridView1.Rows)
        {
            if (dgvr.Cells["FollowedUp"].Value.ToString() == ("No"))
            {
                dgvr.DefaultCellStyle.ForeColor = Color.Red;
            }
        }
¿Fue útil?

Solución 3

public void ColourChange()
    {
        DataGridViewCellStyle RedCellStyle = null;
        RedCellStyle = new DataGridViewCellStyle();
        RedCellStyle.ForeColor = Color.Red;
        DataGridViewCellStyle GreenCellStyle = null;
        GreenCellStyle = new DataGridViewCellStyle();
        GreenCellStyle.ForeColor = Color.Green;


        foreach (DataGridViewRow dgvr in dataGridView1.Rows)
        {
            if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("No"))
            {
                dgvr.DefaultCellStyle = RedCellStyle;
            }
            if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("Yes"))
            {
                dgvr.DefaultCellStyle = GreenCellStyle;
            }
        }
    }

Otros consejos

conectar OnRowDataBound evento a continuación, hacer cosas

ASPX (Grid):

    <asp:.... OnRowDataBound="RowDataBound"..../>

Código Detrás:

    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex == -1)
        {
            return;
        }

        if(e.Row.Cells[YOUR_COLUMN_INDEX].Text=="NO"){
             e.Row.BackColor=Color.Red;   
        }
    }

Para Windows Forms:

hook the **DataBindingComplete** event and do stuff in it:

     private void dataGridView1_DataBindingComplete(object sender, 
                       DataGridViewBindingCompleteEventArgs e)
    {
        if (e.ListChangedType != ListChangedType.ItemDeleted)
        {
            DataGridViewCellStyle red = dataGridView1.DefaultCellStyle.Clone();
            red.BackColor=Color.Red;

            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                if (r.Cells["FollowedUp"].Value.ToString()
                       .ToUpper().Contains("NO"))
                {
                    r.DefaultCellStyle = red;
                }
            }
        }
    }

En su DataGridView, controlar el evento CellFormatting:

dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);

Su controlador de eventos a continuación, podría tener este aspecto:

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

De esta manera usted no está 'iterando' sobre las filas -. Simplemente cambiando el color con el que se pintan / dibujado cuando se hacen visibles (y por lo tanto requieren formato) en la red

¿Es posible que hay espacios o algún otro carácter como parte del valor de la celda? Si es así, intente utilizar el método contiene más que la igualdad recta.

if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("No"))

Esta es la solución para Winforms:

private void HighlightRows()
{
    DataGridViewCellStyle GreenStyle = null;

    if (this.dgridv.DataSource != null)
    {
        RedCellStyle = new DataGridViewCellStyle();
        RedCellStyle.BackColor = Color.Red;

        for (Int32 i = 0; i < this.dgridv.Rows.Count; i++)
        {
            if (((DataTable)this.dgridv.DataSource).Rows[i]["col_name"].ToString().ToUpper() == "NO")
            {
                this.dgridv.Rows[i].DefaultCellStyle = RedCellStyle;
                continue;
            }
        }
    }
}

Este código funciona bien para mí:


foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if ((string)row.Cells["property_name"].Value == UNKNOWN_PROPERTY_NAME)
    {
        row.DefaultCellStyle.BackColor = Color.LightSalmon;
        row.DefaultCellStyle.SelectionBackColor = Color.Salmon;
    }
}

Aparte de fundición como una cadena en lugar de llamar ToString no veo ninguna diferencia lo que podría ser un error de mayúsculas y minúsculas en realidad. Trate de usar:

dgvr.Cells["FollowedUp"].Value.ToString().ToUpper() == "NO"
private void Grd_Cust_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    colorCode == 4 ? Color.Yellow : Color.Brown;
    if (e.RowIndex < 0 || Grd_Cust.Rows[e.RowIndex].Cells["FollowedUp"].Value == DBNull.Value)
        return;
    string colorCode = Grd_Cust.Rows[e.RowIndex].Cells["FollowedUp"].Value.ToString();
    e.CellStyle.BackColor = colorCode == "NO" ? Color.Red : Grd_Cust.DefaultCellStyle.BackColor;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top