如何更改datagridview的行颜色,其中单元格值是c#中的某个值

时间:2014-10-21 06:33:57

标签: c# winforms datagridview

我正在使用win-apps,用c#编码 我有一个datagridview,它从microsoft sql server数据库加载它的数据。 我的需求是我想在datagridview单元格值小于35 的位置设置行颜色。

我的想法如下。

//this is just my Idea,Not correct code,so please add code  
 private void colorchange()
    {
        if (dataGridView4.cellvaue <= 35)
        {
            dataGridView4.row_fore_colour = red;
        }
    }  

datagridview单元格值是文本格式。所以请不要忘记将文本转换为整数值,然后给我一个问题的解决方案(我不知道datagridview单元格值的转换) )

3 个答案:

答案 0 :(得分:1)

void dataGridView4_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (this.dataGridView4.Rows[e.RowIndex].Cells["cellToCheck"].Value != null)
        {
            if ((int)this.dataGridView4.Rows[e.RowIndex].Cells["cellToCheck"].Value <=35)
            {
                this.dataGridView4.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
            }

        }
    }

我在我想要的代码项目中找到了这个..

答案 1 :(得分:0)

认为这可能是这样做的方法:

    for (int i = 0; i < dataGridView4.Rows.Count; i++)
            {
                for (int o = 0; o < dataGridView4.Rows[i].Cells.Count;o++ )
                {  
                     int num1;
                     if(dataGridView4.Rows[i].Cells[o].Value != null)
                     {
                       string text1 = dataGridView4.Rows[i].Cells[o].Value.toString;
                       bool res = int.TryParse(text1, out num1);
                       if (res == true)
                        {
                          if(Convert.ToInt32(dataGridView4.Rows[i].Cells[o].Value) < 35)
                         {
                          dataGridView4.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.Red; 
                         }
                        }
                      }

                }
            }

答案 2 :(得分:0)

尝试这可能是有效的

void dataGridView4_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
for (int i = 0; i < dataGridView4.Rows.Count; i++)
            {
        if (dataGridView4.Rows[i].Cells["cellname"].Value != null)
        {
            if ((int)dataGridView4.Rows[i].Cells["cellname"].Value <=35)
            {
                dataGridView4.Rows[i].DefaultCellStyle.BackColor = Color.Red;
            }
        }
    }
}

这将仅检查一列“cellname”,如果要检查所有列,则添加一个额外的for循环..