如何在datagridview中更改行颜色?

时间:2010-02-03 03:00:12

标签: c# winforms datagridview background-color

我想更改datagridview中特定行的颜色。当columncell 7的值小于columncell 10中的值时,该行应更改为红色。有关如何完成此操作的任何建议吗?

19 个答案:

答案 0 :(得分:173)

您需要遍历datagridview中的行,然后比较每行上第7列和第10列的值。

试试这个:

foreach (DataGridViewRow row in vendorsDataGridView.Rows) 
     if (Convert.ToInt32(row.Cells[7].Value) < Convert.ToInt32(row.Cells[10].Value)) 
     {
         row.DefaultCellStyle.BackColor = Color.Red; 
     }

答案 1 :(得分:55)

我刚刚调查这个问题(所以我知道这个问题大约在3年前发布,但也许它会帮助某些人......)但似乎更好的选择是将代码置于{{1}内事件,所以你不必遍历每一行,只有那些被绘制的行(所以它会在大量数据上表现得更好:

附加到活动

RowPrePaint

事件代码

this.dataGridView1.RowPrePaint 
    += new System.Windows.Forms.DataGridViewRowPrePaintEventHandler(
        this.dataGridView1_RowPrePaint);

答案 2 :(得分:22)

您正在寻找CellFormatting活动 Here就是一个例子。

答案 3 :(得分:21)

我也无法更改文字颜色 - 我从未见过颜色变化。

在我添加代码之前,将文本颜色更改为DataBindingsComplete的事件DataGridView。之后它起作用了。

我希望这能帮助那些面临同样问题的人。

答案 4 :(得分:13)

类似以下内容...假设单元格中的值为整数。

foreach (DataGridViewRow dgvr in myDGV.Rows)
{
  if (dgvr.Cells[7].Value < dgvr.Cells[10].Value)
  {
    dgvr.DefaultCellStyle.ForeColor = Color.Red;
  }
}

未经测试,对任何错误表示歉意。

如果您知道特定行,则可以跳过迭代:

if (myDGV.Rows[theRowIndex].Cells[7].Value < myDGV.Rows[theRowIndex].Cells[10].Value)
{
  dgvr.DefaultCellStyle.ForeColor = Color.Red;
}

答案 5 :(得分:7)

有些人喜欢使用PaintCellPaintingCellFormatting事件,但请注意,更改这些事件中的样式会导致递归调用。如果您使用DataBindingComplete,它将只执行一次。 CellFormatting的参数是仅在可见单元格上调用它,因此您不必格式化不可见的单元格,而是将它们格式化多次。

答案 6 :(得分:4)

您可以使用条件逐行更改Backcolor。在应用Datasource的{​​{1}}后调用此函数。

这是函数。 只需将其复制并放在DatagridView

之后
Databind

答案 7 :(得分:3)

private void dtGrdVwRFIDTags_DataSourceChanged(object sender, EventArgs e)
{
    dtGrdVwRFIDTags.Refresh();
    this.dtGrdVwRFIDTags.Columns[1].Visible = false;

    foreach (DataGridViewRow row in this.dtGrdVwRFIDTags.Rows)
    {
        if (row.Cells["TagStatus"].Value != null 
            && row.Cells["TagStatus"].Value.ToString() == "Lost" 
            || row.Cells["TagStatus"].Value != null 
            && row.Cells["TagStatus"].Value.ToString() == "Damaged" 
            || row.Cells["TagStatus"].Value != null 
            && row.Cells["TagStatus"].Value.ToString() == "Discarded")
        {
            row.DefaultCellStyle.BackColor = Color.LightGray;
            row.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
        }
        else
        {
            row.DefaultCellStyle.BackColor = Color.Ivory;
        }
    }  

    //for (int i= 0 ; i<dtGrdVwRFIDTags.Rows.Count - 1; i++)
    //{
    //    if (dtGrdVwRFIDTags.Rows[i].Cells[3].Value.ToString() == "Damaged")
    //    {
    //        dtGrdVwRFIDTags.Rows[i].Cells["TagStatus"].Style.BackColor = Color.Red;                   
    //    }
    //}
}

答案 8 :(得分:1)

这是我使用bindingDataSource将颜色更改为dataGridView的解决方案:

private void dataGridViewECO_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{            

    if (e.ListChangedType != ListChangedType.ItemDeleted)
    {

        DataGridViewCellStyle green = this.dataGridViewECO.DefaultCellStyle.Clone();
        green.BackColor = Color.Green;

        DataGridViewCellStyle gray = this.dataGridViewECO.DefaultCellStyle.Clone();
        gray.BackColor = Color.LightGray;



        foreach (DataGridViewRow r in this.dataGridViewECO.Rows)
        {

            if (r.Cells[8].Value != null)
            {

                String stato = r.Cells[8].Value.ToString();


                if (!" Open ".Equals(stato))
                {
                    r.DefaultCellStyle = gray;
                }
                else
                {
                    r.DefaultCellStyle = green;
                }
            }

        }

    }
}

答案 9 :(得分:1)

如果绑定到具体对象的(集合),则可以通过该行的DataBoundItem属性获取该具体对象。 (为避免检查单元格中的魔术字符串并使用对象的“真实”属性)

下面的骨架示例:

DTO / POCO

public class Employee
{
    public int EmployeeKey {get;set;}

    public string LastName {get;set;}

    public string FirstName {get;set;}

    public bool IsActive {get;set;}
}       

绑定到datagridview

    private void BindData(ICollection<Employee> emps)
    {
        System.ComponentModel.BindingList<Employee> bindList = new System.ComponentModel.BindingList<Employee>(emps.OrderBy(emp => emp.LastName).ThenBy(emp => emp.FirstName).ToList());
        this.dgvMyDataGridView.DataSource = bindList;
    }       

然后是事件处理程序并获取具体对象(而不是DataGridRow和/或单元格)

        private void dgvMyDataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            Employee concreteSelectedRowItem = this.dgvMyDataGridView.Rows[e.RowIndex].DataBoundItem as Employee;
            if (null != concreteSelectedRowItem && !concreteSelectedRowItem.IsActive)
            {
                dgvMyDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGray;
            }
        }

答案 10 :(得分:0)

喜欢吗?

if (readmesaj.durum11 == "Under")
                                        {
                                            dataGridView1.Rows[i].Cells[1].Style.BackColor = Color.Yellow;
    
                                        }
                                        if (readmesaj.durum11 == "Pass")
                                        {
                                            dataGridView1.Rows[i].Cells[1].Style.BackColor = Color.Green;
    
                                        }
                                        if (readmesaj.durum11 == "Over")
                                        {
                                            dataGridView1.Rows[i].Cells[1].Style.BackColor = Color.Red;
    
                                        }

答案 11 :(得分:0)

如果您是地球上第二个最愚蠢的开发人员(我是最愚蠢的开发人员),那么上述所有解决方案似乎都可以使用:CellFormatting,DataSourceChanged和RowPrePaint。我更喜欢RowPrePaint。

我为此苦苦挣扎(时间太长了),因为在更改所选行时,我需要覆盖SelectionBackColor和SelectionForeColor而不是BackColor和ForeColor。

答案 12 :(得分:0)

我在这里找到了解决我不使用数据绑定的情况的解决方案。没有什么对我有用,但我最终得到了它:

dataGridView.Columns.Clear(); 
dataGridView.Rows.Clear();
dataGridView.Refresh();

答案 13 :(得分:0)

int counter = gridEstimateSales.Rows.Count;

        for (int i = 0; i < counter; i++)
        {
            if (i == counter-1)
            {
                //this is where your LAST LINE code goes
                //row.DefaultCellStyle.BackColor = Color.Yellow;
                gridEstimateSales.Rows[i].DefaultCellStyle.BackColor = Color.Red;
            }
            else
            {
                //this is your normal code NOT LAST LINE
                //row.DefaultCellStyle.BackColor = Color.Red;
                gridEstimateSales.Rows[i].DefaultCellStyle.BackColor = Color.White;
            }
        }

答案 14 :(得分:0)

关于设置DefaultCellStyle.BackColor的说明...您无法将其设置为除Color.Empty之外的任何透明值。这是默认值。这无误地暗示(对我而言)透明色是可以的。他们不是。我设置为透明色的每一行都会绘制所选行的颜色。

在这个问题上,我花了太多时间在墙上撞墙。

答案 15 :(得分:0)

使用此代码,您只需更改行backcolor,其中columname值为null,其他行仍为默认值。

       foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells["columnname"].Value != null)
                    {
                        dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.MistyRose;
                    }
                 }

答案 16 :(得分:0)

您尚未提及价值如何变更。当用户输入值时,我使用了类似的功能。即进入和离开编辑模式。

使用datagridview的 CellEndEdit 事件。

private void dgMapTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    double newInteger;

    if (double.TryParse(dgMapTable[e.ColumnIndex,e.RowIndex].Value.ToString(), out newInteger)
    {
        if (newInteger < 0 || newInteger > 50)
        {
            dgMapTable[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red; 

            dgMapTable[e.ColumnIndex, e.RowIndex].ErrorText 
                = "Keep value in Range:" + "0 to " + "50";
        }
    }                               
}

您可以以类似的方式添加清除错误通知的逻辑。

如果在您的情况下,如果以编程方式加载数据,那么 CellLeave 事件可以与相同的代码一起使用。

答案 17 :(得分:0)

适用于Visual Studio 2010.(我试了一下,它的确有效!) 它将绘制整行。

  1. datagridview
  2. 创建一个按钮
  3. 创建一个CellClick事件并将下一行代码放在其中。

  4. if (dataGridView3.Columns[e.ColumnIndex].Index.Equals(0)    
    {
        dataGridView3.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Beige;
    }
    

答案 18 :(得分:0)

我通常喜欢使用GridView.RowDataBound事件事件。

protected void OrdersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.ForeColor = System.Drawing.Color.Red;
    }
}
相关问题