How can I color rows in datagridview with conditio

2019-09-13 08:42发布

I want with a condition :

  • all rows have bool_badge =0 : color with RED
  • all rows have bool_badge=1 : color with ForestGreen

I have a code Correct BUT just when i click for a cell specific

My code:

foreach (DataGridViewRow dr in dataGridView1.Rows)
        {              
            int row = this.dataGridView1.CurrentCell.RowIndex;
            string valeur = dataGridView1[2, row].Value.ToString();

            if (valeur == "0")
            {
                dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
            }
            else
            {
                dataGridView1.DefaultCellStyle.SelectionBackColor = Color.ForestGreen;
            }
        }

The Result : 1) enter image description here`

2) enter image description here

But I want when i execute my application , the test begin if bool_badge 0 or 1, and i have for all the gridview : color RED or ForestGreen ,

I try this code:

for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {                
            string valeur = dataGridView1[2, i].Value.ToString();

            if (valeur == "0")
            {
                dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
            }
            else
            {
                dataGridView1.DefaultCellStyle.SelectionBackColor = Color.ForestGreen;
            }
        }

But i have ERROR!

this is :

enter image description here

How can i fix it?

Very thanks,

3条回答
对你真心纯属浪费
2楼-- · 2019-09-13 09:05

For helping you debugging don't do Value.ToString(); just

 var value = dataGridView_XXX.Rows[rowNumber].Cells[i].value;

And

if (value == null) display your row/column index
else dataGridView_XXX.Rows[rowNumber].DefaultCellStyle.BackColor = xxx;
查看更多
The star\"
3楼-- · 2019-09-13 09:07

You should use .Rows and .Cells properties.

string valeur = dataGridView1.Rows[i].Cells[2].Value.ToString();
查看更多
Lonely孤独者°
4楼-- · 2019-09-13 09:13

You can use Datagridview's Cell_Formatting event.

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].HeaderText == "bool_badge" && dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null) 
         // if the column is bool_badge and check null value for the extra row at dgv
            {
                    if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "0")
                    {
                        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                    }
                    if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "1")
                    {
                        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.ForestGreen;
                    }
            }
        }

Result will be,

enter image description here

Hope helps,

查看更多
登录 后发表回答