ASP.NET中为DataGrid添加合计字段
在 Page_Load 事件中,你所要做的就是连接到 SQL Server 并执行一个简单的 SqlCommand。 你取得了所有 Price 值>0 的 title 和 price 数据。你使用 SqlCommand.ExecuteReader 方法返回一个 SqlDataReader 并将其直接绑定到 DataGrid (MyGrid)。
("server=Localhost;database=pubs;uid=sa;pwd=;");
//创建SQL连接
SqlCommand myCommand = new SqlCommand
("SELECT title, price FROM Titles WHERE price > 0", myConnection);
//创建SQL命令
try
{
myConnection.Open();//打开数据库连接
MyGrid.DataSource = myCommand.ExecuteReader();
//指定 DataGrid 的数据源
MyGrid.DataBind();//绑定数据到 DataGrid
myConnection.Close();//关闭数据连接
}
catch(Exception ex)
{
//捕获错误
HttpContext.Current.Response.Write(ex.ToString());
}
}
ListItemType.AlternatingItem)
{
CalcTotal( e.Item.Cells[1].Text );
e.Item.Cells[1].Text = string.Format("{0:c}",
Convert.ToDouble(e.Item.Cells[1].Text));
}
else if(e.Item.ItemType == ListItemType.Footer )
{
e.Item.Cells[0].Text="Total";
e.Item.Cells[1].Text = string.Format("{0:c}", runningTotal);
}
}