簡體   English   中英

如何根據 Asp.net Gridview 中的文本更改單元格的顏色

[英]How to Change Cell's Color Based on text in Asp.net Gridview

我在考勤門戶網站上工作在此處輸入圖片說明

我想根據單元格中的文本更改單元格顏色,例如,如果單元格包含“P”,則其背景顏色必須為綠色,而對於“A”,則必須為紅色。 如何實現這一目標?

這是使用 OnRowDataBound 的另一種方法

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TableCell cell = e.Row.Cells[3];
        string data = cell.Text;
        if (data == "A")
        {
            cell.BackColor = Color.Red;
        }
        else if (data == "P")
        {
            cell.BackColor = Color.Green;
        }
        
    }
}

您好,這里有一種方法可以做到這一點:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TableCell cell = e.Row.Cells[1];
        int quantity = int.Parse(cell.Text);
        if (quantity == 0)
        {
            cell.BackColor = Color.Red;
        }
        if (quantity > 0 && quantity <= 50)
        {
            cell.BackColor = Color.Yellow;
        }
        if (quantity > 50 && quantity <= 100)
        {
            cell.BackColor = Color.Orange;
        }
    }
}

在本例中,您只檢查第二個單元格 (e.Row.Cells[2])
你可以為你自己的例子做一個 for 循環,如下所示:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
  {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
          for (int i = 0; i < e.Row.Cells.Count; i++)
          {
              
              TableCell cell = e.Row.Cells[i];

              int quantity = int.Parse(cell.Text);
              if (quantity == 0)
              {
                  cell.BackColor = Color.Red;
              }
              if (quantity > 0 && quantity <= 50)
              {
                  cell.BackColor = Color.Yellow;
              }
              if (quantity > 50 && quantity <= 100)
              {
                  cell.BackColor = Color.Orange;
              }
          }
      }
  }

這是我為解決此問題所做的工作:

    protected void Grid1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
    
        
          if (e.Row.RowType == DataControlRowType.DataRow)
          {
    
          int colCount = e.Row.Cells.Count;
          for (int i = 2; i < colCount; i++)
           {
              if (e.Row.Cells[i].Text == "A")
              {
                e.Row.Cells[i].BackColor = System.Drawing.Color.Red;
                e.Row.Cells[i].ForeColor = System.Drawing.Color.White;
              }
              if (e.Row.Cells[i].Text == "P")
              {
                e.Row.Cells[i].BackColor = System.Drawing.Color.Green;
                e.Row.Cells[i].ForeColor = System.Drawing.Color.White;
              }
           }
          }
    }

暫無
暫無

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

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