GridView 格式化特定值

     如果希望格式化某个特定的行甚至某个单元格,解决方法是相应GridView。RowDataBind事件,该事件在网格的一部分(标题,题注,分页,普通行或交替数据行,选定项目)被创建时发生。GridViewRow.DataItem属性提供指定行的数据对象,而通过 GridViewRow.Cells集合可以读取行的内容,通过GridViewRow可以改变颜色和对齐方式,增加或删除子控件等。
    下面的示例处理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;
            }

        }


    }

  
                    

  这里使用DataBinder.Eval方法通过反射从数据中读取信息


posted @ 2009-09-21 22:35  i'm zjz  阅读(451)  评论(0编辑  收藏  举报