簡體   English   中英

如何根據單元格的值更改 DataGridView 中一行的背景色?

[英]How to change the backcolor of a row in a DataGridView based on the value of a cell?

我有一個 DataGridView,它顯示了 DataTable 的內容。

我想根據該行單元格的值設置該行的背景色。

請注意,有問題的單元格位於 DataGridView 中未顯示的列中 (Visible=False)。

如果您處理 RowDataBound 事件,您可以檢查數據的值並修改單元格的屬性或在該事件處理程序中應用不同的樣式。

protected void Page_Load(object sender, EventArgs e)
{
    GridView g1 = new GridView();
    g1.RowDataBound += new GridViewRowEventHandler(g1_RowDataBound);
}

void g1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        // Check the Value
        if(e.Row.Cells[1].Text = someValue)
        {
            e.Row.Cells[1].CssClass = "colorCellRed";
        }

    }
}

那應該給你你正在尋找的東西。 如果您需要 VB 而不是 C#,請告訴我。

祝你好運!

RowDataBound,如前所述; 您還可以檢查數據對象的值,以及網格本身的文本:

void gridView_DataBound(object sender, GridViewEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    var myObject = (myObject)e.DataItem;
    if (myObject.IsOverdue())
    {
      e.Row.CssClass = "overdue";
    }
  }
}

另一種選擇是使用 CellFormatting 事件。 第一個選項顯示訪問綁定數據項,如果您沒有為相關數據設置列,則該選項很有用。 如果有一個列,無論它是否可見,第二個選項都有效。

    private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (((MyDataObject)dataGridView.Rows[e.RowIndex].DataBoundItem).Condition == Value)
            {
                e.CellStyle.BackColor = System.Drawing.Color.Gold;

            }
        }

// 選項二 -- 可以使用 ColumnIndex 而不是 ColumnName

    private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridView["ColumnName", e.RowIndex].Value).Condition == TargetValue)
            {
                e.CellStyle.BackColor = System.Drawing.Color.Gold;

            }
        }

暫無
暫無

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

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