缓慢实例:
思路:直接对服务器端的数据库进行查询,然后填充到gridview,显示在网页上面。
{
string sqlconn = @"Data Source=IP;Initial Catalog=DATABASENAME;Integrated Security=True;userId=sa;PassWord=PASSWORD"; SqlConnection conn = new SqlConnection(sqlconn); conn.Open(); string mysql = "select ID, COL1,COL2,COL3 from TABLE where DATE BETWEEN '" + 2012/11/12+ "'and '" + 2012/11/28 + "'"; DataSet ds = new DataSet(); SqlDataAdapter sda = new SqlDataAdapter(mysql, conn); sda.Fill(ds); GridView1.DataSource = ds.Tables[0].DefaultView; GridView1.DataBind(); //改变表头
int count = this.GridView1.HeaderRow.Cells.Count;//列数
for (int i = 0; i < count; i++) { string oldValue = this.GridView1.HeaderRow.Cells[i].Text; if (oldValue == "ID") { this.GridView1.HeaderRow.Cells[i].Text = "序号"; } else if (oldValue == "COL1") { this.GridView1.HeaderRow.Cells[i].Text = "列1名"; } else if (oldValue == "COL2") { this.GridView1.HeaderRow.Cells[i].Text = "列2名"; } else if (oldValue == "COL3") { this.GridView1.HeaderRow.Cells[i].Text = "列3名" } } conn.Close();
}
改进方案:
思路:对服务器端的数据库查询与填充分离,先对数据库进行查询,将查询结果放到一个新的数据源上边,然后让gridview直接连接到新的数据源,再在网页上显示。
首先在设计视图添加“数据源”(SqlDataSource),设置如下
connectionstring ="连接字符串",代码如下
{ SqlDataSource1.ConnectionString = ConfigurationManager.AppSettings["connString"]; string mysql = "select ID AS '序号',COL1 AS '列1名',COL2 AS '列2名',COL3 AS'列3名' from TABLE where DATE BETWEEN '" + 2012/11/12 + "'and '" + 2012/11/28+ "'"; SqlDataSource1.SelectCommand = mysql ; }
gridview属性设置如下