Question

J'ai un datagridview composé de plusieurs lignes et colonnes. Je veux parcourir chaque ligne et vérifier le contenu d'une colonne spécifique. Si cette colonne contient le mot « NON », je veux changer le forecolor de toute la ligne rouge. Voici une tentative d'un code à ce jour, mais il est certainement pas de travail, commence à me demander si je dois itérer sur chaque cellule?

CODE:

foreach (DataGridViewRow dgvr in dataGridView1.Rows)
        {
            if (dgvr.Cells["FollowedUp"].Value.ToString() == ("No"))
            {
                dgvr.DefaultCellStyle.ForeColor = Color.Red;
            }
        }
Était-ce utile?

La solution 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;
            }
        }
    }

Autres conseils

brancher OnRowDataBound évènement puis faire des choses

ASPX (grille):

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

Derrière le code:

    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;   
        }
    }

WinForms:

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;
                }
            }
        }
    }

Sur votre DataGridView, gérer l'événement CellFormatting:

dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);

Votre gestionnaire d'événements pourrait alors ressembler à ceci:

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 cette façon, vous n'êtes pas « itérez » sur les lignes -. Changeant simplement la couleur avec laquelle ils sont peints / tirés quand ils deviennent visibles (et nécessitent donc la mise en forme) dans la grille

Est-il possible il y a des espaces ou un autre caractère dans le cadre de la valeur de la cellule? Si oui essayez d'utiliser la méthode Contains plutôt que l'égalité droit.

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

Ceci est la solution pour 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;
            }
        }
    }
}

Ce code fonctionne bien pour moi:


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;
    }
}

Autre que la coulée sous forme de chaîne plutôt que d'appeler ToString je ne vois pas vraiment de différence il pourrait être un bug cas de sensibilité. Essayez d'utiliser:

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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top