通过使用GridView控件,我们可以让它访问数据库,进而显示数据库中表的内容,GridView访问数据库的方法的有两种,一种是通过代码实现,另一种则是直接绑定数据源。
首先,在web窗体的设计界面,从工具箱出拉出一个GridView控件,然后通过以下的方法显示数据库中的数据。
1、通过代码实现(.aspx.cs文件):
先连接数据库----用DataAdapter/DataReader访问数据库,并执行sql语句,获取所需要的数据,直接读取,或储存到特定的容器中,如DataSet。在.aspx.cs文件中添加如下代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
string Constr="server=localhost; uid=sa;pwd=123456;database=NorthWind";
string sqlstr="select * from Products";
SqlConnection con = new SqlConnection(Constr);
SqlDataAdapter ad = new SqlDataAdapter(sqlstr, con);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
2、直接绑定:
创建数据源----配置数据源:设置所对于的表以及SQL查询语句----完成绑定。
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;public partial class GridView_Export_Excel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
string Constr="server=localhost; uid=sa;pwd=123456;database=NorthWind";
string sqlstr="select * from Products";
SqlConnection con = new SqlConnection(Constr);
SqlDataAdapter ad = new SqlDataAdapter(sqlstr, con);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=MyExcel.doc");
Response.ContentType = "application/word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{}
}