How can I color rows in datagridview with condition C#

馋奶兔 提交于 2019-12-12 04:16:46

问题


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) `

2)

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 :

How can i fix it?

Very thanks,


回答1:


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,

Hope helps,




回答2:


You should use .Rows and .Cells properties.

string valeur = dataGridView1.Rows[i].Cells[2].Value.ToString();



回答3:


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;


来源:https://stackoverflow.com/questions/40378386/how-can-i-color-rows-in-datagridview-with-condition-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!