簡體   English   中英

如何更改datagridview中的行顏色

[英]How to change row color in datagridview

我想更改我的 datagridview 中特定行的顏色。 當 columncell 7 的值小於 columncell 10 中的值時,該行應更改為紅色。有關如何完成此操作的任何建議?

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

我只是在調查這個問題(所以我知道這個問題是在大約 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;
    }
}

您正在尋找CellFormatting事件。
是一個例子。

我也無法更改文本顏色 - 我從未見過顏色變化。

直到我添加代碼以將文本顏色更改為DataGridView的事件DataBindingsComplete 之后它起作用了。

我希望這將幫助面臨同樣問題的人。

類似於以下內容...假設單元格中的值是整數。

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

有些人喜歡使用PaintCellPaintingCellFormatting事件,但請注意,更改這些事件中的樣式會導致遞歸調用。 如果您使用DataBindingComplete它只會執行一次。 CellFormatting的參數是它僅在可見單元格上調用,因此您不必格式化不可見單元格,但您可以多次格式化它們。

您可以使用您的條件逐行更改Backcolor 。在應用DatagridViewDatasource后調用此函數。

這是它的功能。 只需復制它並將其放在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;
    }
}
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;                   
    //    }
    //}
}

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

        }

    }
}

如果綁定到具體對象的(集合),則可以通過行的 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;
            }
        }

我通常喜歡為此使用 GridView.RowDataBound 事件事件。

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

適用於 Visual Studio 2010。(我試過了,它有效!)它將繪制你的整行。

  1. datagridview創建一個按鈕。
  2. 創建一個CellClick事件並將下一行代碼放入其中。

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

你沒有提到價值是如何改變的。 當用戶輸入值時,我使用了類似的功能。 即進入和離開編輯模式。

使用 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事件可以與相同的代碼一起使用。

使用此代碼,您只需更改 columname 值為 null 的行背景顏色,其他行顏色仍然是默認顏色。

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

只是關於設置DefaultCellStyle.BackColor ...您不能將其設置為除Color.Empty之外的任何透明值。 這是默認值。 這錯誤地暗示(對我來說,無論如何)透明顏色是可以的。 他們不是。 我設置為透明顏色的每一行只繪制選定行的顏色。

我花了太多時間在這個問題上撞牆。

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

我來到這里為我不使用數據綁定的情況尋找解決方案。 沒有什么對我有用,但我最終得到了它:

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

如果您是地球上第二個最笨的開發人員(我是最笨的),那么上述所有解決方案似乎都有效:CellFormatting、DataSourceChanged 和 RowPrePaint。 我更喜歡 RowPrePaint。

我為此苦苦掙扎(太久了),因為在更改所選行時,我需要覆蓋我的 SelectionBackColor 和 SelectionForeColor 而不是 BackColor 和 ForeColor。

dataGridView1.Rows[1].Cells[1].Style.BackColor = Color.Yellow;


    

if (this.dgblista.Columns[e.ColumnIndex].Name == "TOTAL PAGADO") { if ((dgblista.Columns[e.ColumnIndex].Name == "COSTO DEL CURSO") == (dgblista.Columns[ e.ColumnIndex].Name == "TOTAL PAGADO")) { e.CellStyle.ForeColor = Color.White; e.CellStyle.BackColor = 顏色.紅色; } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM