![](/img/trans.png)
[英]ASP.NET Change Text and Color in Gridview cell in a Template Field
[英]How to Change Cell's Color Based on text in Asp.net Gridview
這是使用 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.