Gridview有一个runat =“server”标签

时间:2014-08-22 18:47:47

标签: asp.net pdf gridview response

我已将iTextSharp添加到“Project> ... Add References”并将其添加到使用:

using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;  

我在aspx中已经有一个runat =“server”标签:

<asp:GridView ID="GridView1" runat="server"></asp:GridView>

但我在第“GridView1.RenderControl(hw);

行获取错误代码
 Control 'MainContent_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

Button1_Click代码:

protected void Button1_Click(Object sender,System.EventArgs e)
    {
        string connStr = ConfigurationManager.ConnectionStrings["PDFMDF"].ConnectionString;
        DataSet ds = new DataSet();
        try
        {
            string cmdStr = "SELECT * FROM [GridviewTable];";
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                        GridView1.DataSource = ds;
                        GridView1.DataBind();
                    }
                    conn.Close();
                    cmd.Dispose();
                    conn.Dispose();
                }
            }
        }
        catch  (Exception ex)
        {
            TextBox1.Text = ex.ToString();
        }

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=this.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        GridView1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document PDFdoc = new Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F);
        iTextSharp.text.html.simpleparser.HTMLWorker htmlparser =   new iTextSharp.text.html.simpleparser.HTMLWorker(PDFdoc);
        PdfWriter.GetInstance(PDFdoc, Response.OutputStream);
        PDFdoc.Open();
        htmlparser.Parse(sr);
        PDFdoc.Close();
        Response.Write(PDFdoc);
        Response.End();
    }

1 个答案:

答案 0 :(得分:1)

错误意味着GridView必须位于如下形式:

<form id="FormId" runat="server">
   <asp:GridView ID="GridView1" runat="server"></asp:GridView>
</form>