/// <summary>
/// 绑定GridView时(RowDataBound)添加一些属性
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//行单元格从0开始数
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "yes=this.style.backgroundColor; this.style.backgroundColor='red'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=yes");
//获取绑定行的book对象
Book book = (Book)e.Row.DataItem;
//给 价格 的单元格添加color颜色
if (book.UnitPrice < 80)
{
e.Row.Cells[8].Attributes.Add("style", "color:green");
// e.Row.Cells[6].Text = "便宜";
}
else if (book.UnitPrice < 200)
{
e.Row.Cells[8].Attributes.Add("style", "color:yellow");
}
else
{
e.Row.Cells[8].Attributes.Add("style", "color:red");
}
this.sumPrice += Convert.ToSByte(book.UnitPrice); //累加价格(方便计算平均价格)
//序号1,2,3......
String num = Convert.ToString(e.Row.RowIndex + 1);
e.Row.Cells[0].Text = num;
//判断内容的字数是否大于20,如果大于,就是只显示20个字符+....
if (book.ContentDescription.Length > 20)
{
e.Row.Cells[5].Text = book.ContentDescription.Substring(0, 20) + "...";
}
//隐藏列
// e.Row.Cells[6].Attributes.Add("style", "display:none"); //隐藏数据列
}
else if (e.Row.RowType == DataControlRowType.Footer) //判断是不是脚注行
{
e.Row.Cells[7].Text = "均价";
float avgPrice = sumPrice / this.gvBook.Rows.Count; //注:Rows不包含标头行和脚注行
String money = String.Format("{0:C2}", avgPrice); //格式化均价(以货币的形式显示)
e.Row.Cells[8].Text = money;
}
}