【发布时间】:2011-05-24 14:13:53
【问题描述】:
我需要区分两个连续的单元格。
当数据绑定到网格视图时,如果它们具有不同的值,则连续的每一个。
所以,如果在第 1 行有单元格“ABC”,在第 2 行有单元格“CBA”。
我需要为每个单元格涂上不同的颜色。
最好的方法是什么?
【问题讨论】:
我需要区分两个连续的单元格。
当数据绑定到网格视图时,如果它们具有不同的值,则连续的每一个。
所以,如果在第 1 行有单元格“ABC”,在第 2 行有单元格“CBA”。
我需要为每个单元格涂上不同的颜色。
最好的方法是什么?
【问题讨论】:
这称为条件格式
您可以在标记中启用 RowDataBound 事件
<asp:GridView ID="gridview1" runat="server" OnRowDataBound="RowDataBound">
</asp:GridView>
并将其放入您的代码隐藏文件中。
protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
if(e.Row.RowIndex == 0) // This is row no.1
if(e.Row.Cells[0].Text == "ABC")
e.Row.Cells[0].BackColor = Color.Red;
if(e.Row.RowIndex == 1) // This is row no.2
if(e.Row.Cells[0].Text == "CBA")
e.Row.Cells[0].BackColor = Color.Green;
}
}
【讨论】:
在页面 OnRowDataBound="gridView1_DataBinding" 的 html 部分中添加到您的 gridview。然后添加事件处理程序代码隐藏:
protected void gridView1_DataBinding(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;
var c = e.Row.FindControl("IdOfControl") as Label;
if(c != null)
{
if (c.Text == "ABC")
e.Row.BackColor = GetColor("Gray");
if (c.Text == "BCA")
e.Row.BackColor = GetColor("Green");
}
}
private Color GetColor(string color)
{
return Color.FromName(color);
}
最好的问候,迪玛。
【讨论】:
如果我理解正确,您想更改单元格的颜色,具体取决于它的值。 如果正确,您可以这样尝试:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((Label)e.Row.Cells[0].FindControl("ValueHoldingControl").Text == "ABC")
{
//Coloring the cell
}
}
}
【讨论】:
您可以在 gridview 的 rowdatabound 事件上执行此操作。将上一行保留在视图状态或会话中,并将其与下一行匹配。如果不匹配,请更改颜色,否则不要更改。
【讨论】:
void gvShowFullDetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#AECD6F");
}
}
【讨论】: