首页 文章

如何在datagridview中更改行颜色?

提问于
浏览
118

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

17 回答

  • 163

    您需要遍历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; 
         }
    
  • 7

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

    附加到活动

    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;
        }
    }
    
  • 1

    你正在寻找CellFormatting事件 .
    Here就是一个例子 .

  • 22

    我也无法更改文本颜色 - 我从未看到颜色变化 .

    直到我添加代码以将文本颜色更改为事件 DataBindingsComplete for DataGridView . 之后它起作用了 .

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

  • 1

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

    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;
    }
    
  • 19

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

  • 4

    您可以使用条件逐行更改 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;
        }
    }
    
  • 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;                   
        //    }
        //}
    }
    
  • 0

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

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

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

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

    适用于Visual Studio 2010.(我试过了,它的工作原理!) It will paint your entire row.

    • datagridview 创建一个按钮 .

    • 创建一个 CellClick 事件并将下一行代码放在其中 .


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

    您还没有提到 Value 如何变化 . 当用户输入值时,我使用了类似的功能 . 即进入和离开编辑模式 .

    使用 CellEndEdit datagridview事件 .

    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 事件可以与相同的代码一起使用 .

  • 0

    使用此代码,您只能更改行backcolor,其中columname值为null其他行color仍然是默认值 .

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

    只是关于设置 DefaultCellStyle.BackColor 的注释...除了 Color.Empty 之外,您无法将其设置为任何透明值 . 那个's the default value. That falsely implies (to me, anyway) that transparent colors are OK. They'不是 . 我设置为透明颜色的每一行都会绘制所选行的颜色 .

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

  • 13

    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;
                }
            }
    
  • 0

    我登陆这里寻找一个解决方案,我不使用数据绑定 . 没有什么对我有用,但我最终得到它:

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

相关问题