下面的示例处理RowDataBound时间并按如下的规则设置颜色
1. 如果称呼是Ms或Mrs,则将背景设为粉色,前景设为栗色。
2. 如果称呼是Mr,背景色设为深蓝色,前景色为淡青色。
3. 对于其他通用称呼入Dr,则呈现通过GridView.BackColor属性设置背景颜色
RowDataBound事件代码如下:
protected
void
gridEmployees_RowDataBound(
object
sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get the title of courtesy for the item that's being created.
string title = (string)DataBinder.Eval(e.Row.DataItem, "TitleOfCourtesy");
// If the title of courtesy is "Ms.", "Mrs.", or "Mr.",
// change the item's colors.
if (title == "Ms." || title == "Mrs.")
{
e.Row.BackColor = System.Drawing.Color.LightPink;
e.Row.ForeColor = System.Drawing.Color.Maroon;
}
else if (title == "Mr.")
{
e.Row.BackColor = System.Drawing.Color.LightCyan;
e.Row.ForeColor = System.Drawing.Color.DarkBlue;
}
}
}
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get the title of courtesy for the item that's being created.
string title = (string)DataBinder.Eval(e.Row.DataItem, "TitleOfCourtesy");
// If the title of courtesy is "Ms.", "Mrs.", or "Mr.",
// change the item's colors.
if (title == "Ms." || title == "Mrs.")
{
e.Row.BackColor = System.Drawing.Color.LightPink;
e.Row.ForeColor = System.Drawing.Color.Maroon;
}
else if (title == "Mr.")
{
e.Row.BackColor = System.Drawing.Color.LightCyan;
e.Row.ForeColor = System.Drawing.Color.DarkBlue;
}
}
}
这里使用DataBinder.Eval方法通过反射从数据中读取信息