Click here to Skip to main content
14,775,221 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear All,


C# question!

I would like to change a cell color in datagridview if it is equal with an other string.

Could you help me?

Thx!
Posted
Comments
Maciej Los 12-Feb-15 6:41am
   
What have you tried?
TheRealSteveJudge 12-Feb-15 6:42am
   
WPF or Windows Forms?

Use the DataGridView.RowPrePaint event[^] - it's called just before the whole row is painted, and allows you to set the appropriate cell Style property to whatever you need.

[edit]typos[/edit]
   
v2
If it is a windows form project you can use the following:

Add int the designer the next line to subscribe to the Cell end edit event:
this.dataGridView1.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEndEdit);


And in the event handler you verify with you string:

private static const string yourString = "XYZ";

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dataGridView = (DataGridView)sender;

    if (dataGridView.CurrentCell.Value.ToString() == yourString)
    {
        dataGridView.CurrentCell.Style.ForeColor = Color.Red;
    }

}


You can verify for duplicates by going thru all the cells:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dataGridView = (DataGridView)sender;

    // Iterate thru all the cell and verifying if the text is a duplicate.
    for (int i = 0; i < dataGridView.ColumnCount; i++)
    {
        for (int j = 0; j < dataGridView.RowCount; j++)
        {
            if (dataGridView.Rows[j].Cells[i].Value != null)
            {
                if (dataGridView.Rows[j].Cells[i].Value.ToString() == dataGridView.CurrentCell.Value.ToString() && dataGridView.Rows[j].Cells[i] != dataGridView.CurrentCell)
                {
                    dataGridView.CurrentCell.Style.ForeColor = Color.Red;

                    // Optional you can set the value of the cell where you find the text
                    dataGridView.Rows[j].Cells[i].Style.ForeColor = Color.Red;

                }
            }
        }
    }
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900