将sql server中数据以Excel格式显示在浏览器的问题
如题,程序在dgExcel.RenderControl(hw)出错:类型“GridView”的控件“dgExcel”必须放在具有 runat=server 的窗体标记内。代码如下:
protected void Page_Load(object sender, EventArgs e)
{
String strsql;
DataSet objDataset = new DataSet();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings[ "GoodsConnectionString "].ToString();
strsql = "select * from products ";
SqlDataAdapter objAdapter = new SqlDataAdapter();
con.Open();
objAdapter.SelectCommand = new SqlCommand(strsql, con);
objAdapter.Fill(objDataset);
//dgExcel是Gridview的id
DataView oView = new DataView(objDataset.Tables[0]);
dgExcel.DataSource = oView;
dgExcel.DataBind();
con.Close();
con.Dispose();
con = null;
if (Request.QueryString[ "bExcel "] == "1 ")//另一页面穿的值
{
Response.ContentType = "application/vnd.ms-excel ";
Response.Charset = " ";
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
dgExcel.RenderControl(hw);//程序在此出错
Response.Write(tw.ToString());
Response.End();
}
检查 <form id= "form1 " runat= "server "> 在,无丢失
------解决方案--------------------加上
public override void VerifyRenderingInServerForm( Control control )