160

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

4

19 回答 19

224

您需要遍历 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; 
     }
于 2010-02-03T15:25:09.577 回答
71

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

附加到事件

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

事件代码

private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
    if (Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[7].Text) < Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[10].Text)) 
    {
        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Beige;
    }
}
于 2012-10-21T14:01:48.247 回答
26

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

于 2010-02-03T03:02:43.210 回答
21

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

直到我添加代码以将文本颜色更改DataBindingsCompleteDataGridView. 之后它起作用了。

我希望这将帮助面临同样问题的人。

于 2012-11-26T07:52:29.237 回答
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;
}
于 2010-02-03T04:04:12.773 回答
9

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

于 2013-02-25T19:50:42.593 回答
5

Backcolor您可以使用您的条件逐行更改。并且在应用Datasource后调用此函数DatagridView

这是它的功能。只需复制它并将其放在后面Databind

private void ChangeRowColor()
{
    for (int i = 0; i < gvItem.Rows.Count; i++)
    {
        if (BindList[i].MainID == 0 && !BindList[i].SchemeID.HasValue)
            gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#C9CADD");
        else if (BindList[i].MainID > 0 && !BindList[i].SchemeID.HasValue)
            gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#DDC9C9");
        else if (BindList[i].MainID > 0)
            gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#D5E8D7");
        else
            gvItem.Rows[i].DefaultCellStyle.BackColor = Color.White;
    }
}
于 2014-10-01T11:17:00.097 回答
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;                   
    //    }
    //}
}
于 2010-12-03T11:34:54.147 回答
2

这是我使用 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;
                }
            }

        }

    }
}
于 2015-10-07T07:42:20.667 回答
2

如果绑定到具体对象的(集合),则可以通过行的 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;}
}       

绑定到数据网格视图

    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;
            }
        }
于 2017-04-25T15:51:00.250 回答
0

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

protected void OrdersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.ForeColor = System.Drawing.Color.Red;
    }
}
于 2010-02-04T02:49:42.637 回答
0

适用于 Visual Studio 2010。(我试过了,它有效!) 它将绘制你的整行。

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

if (dataGridView3.Columns[e.ColumnIndex].Index.Equals(0)    
{
    dataGridView3.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Beige;
}
于 2014-10-29T13:53:55.627 回答
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事件可以与相同的代码一起使用。

于 2014-12-19T07:02:04.607 回答
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;
    
                                        }
于 2021-03-14T15:58:12.283 回答
0

使用此代码,您只需更改 columname 值为 null 的行背景颜色,其他行颜色仍然是默认颜色。

       foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells["columnname"].Value != null)
                    {
                        dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.MistyRose;
                    }
                 }
于 2016-08-30T13:12:41.977 回答
0

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

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

于 2020-03-06T20:42:26.383 回答
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;
    }
}
于 2017-08-17T09:02:32.400 回答
0

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

dataGridView.Columns.Clear(); 
dataGridView.Rows.Clear();
dataGridView.Refresh();
于 2018-06-08T02:12:22.987 回答
0

只是关于设置的注释DefaultCellStyle.BackColor......你不能将它设置为任何透明值,除了Color.Empty. 这是默认值。这错误地暗示(对我来说,无论如何)透明颜色是可以的。他们不是。我设置为透明颜色的每一行只绘制选定行的颜色。

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

于 2017-02-02T22:34:08.043 回答