ASP.NET - 当EnableViewState设置为False时检索网格视图数据

时间:2016-08-02 14:34:34

标签: c# asp.net gridview

我正在构建一个需要在GridView控件中显示数据的应用程序,按特定值分组,然后将其导出为PDF。我在这里使用这组类(http://www.agrinei.com/gridviewhelper/gridviewhelper_pt.htm)进行分组,然后效果很好。但是,我必须将EnableViewState设置为false才能正常工作。当我需要将其导出为PDF时,问题就出现了。以前(在使用GridViewHelper之前),这是有效的。但是,它现在生成一个空报告(我想因为EnableViewState为false)。

如何保存通过使用GridViewHelper类生成的GridView的数据和结构,以便将其导出为PDF?

我的一些aspx(为简洁起见省略了部分代码)

public partial class all : System.Web.UI.Page
{
    Int32 userID;
    Int32 currentID;

    protected void Page_Load(object sender, EventArgs e)
    {
        GridViewHelper helper = new GridViewHelper(allTicketGrid);
        helper.RegisterGroup("propName", true, true);
        helper.ApplyGroupSort();
        userID = Convert.ToInt32(Session["userID"]);
        if (Session["userLevel"] == null || Session["userLevel"] == "")
        {
            Response.Redirect("~/Default.aspx");
        }

      if (!IsPostBack)
       {

           this.populate();
        }
    }

    protected void populate()
    {
        toDateBox.Text = DateTime.Now.ToShortDateString();
        fromDateBox.Text = DateTime.Now.ToShortDateString();
        using (ticketModel dbContext = new ticketModel())
        {


           END_USER user = dbContext.END_USER.First(u => u.END_USER_ID == userID);

            itemCheckBoxList.DataSource = dbContext.ITEM_TYPE.ToList();
            itemCheckBoxList.DataTextField = "DESCRIPTION";
            itemCheckBoxList.DataValueField = "ITEM_TYPE_ID";
            itemCheckBoxList.DataBind();

            List<Int32> propIDList = new List<Int32>();

            foreach(END_USER_PROPERTY item in user.END_USER_PROPERTY.ToList() ) {
                propIDList.Add((Int32)item.PROPERTY_ID);
            }
            locationCheckBoxList.DataSource = dbContext.PROPERTies.Where(p=> propIDList.Contains(p.PROPERTY_ID)).ToList();
            locationCheckBoxList.DataTextField = "SHORT_NAME";
            locationCheckBoxList.DataValueField = "PROPERTY_ID";
            locationCheckBoxList.DataBind();


        }
    }

    protected void exportReport(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

      for (int i = 0; i < allTicketGrid.Columns.Count; i++)
        {
            dt.Columns.Add(allTicketGrid.Columns[i].HeaderText);
        }
        foreach (GridViewRow rowView in allTicketGrid.Rows)
        {
            DataRow dr = dt.NewRow();

           for (int i = 0; i < rowView.Cells.Count; i++)
            {

                dr[i] = rowView.Cells[i].Text.Trim();
            }
           dt.Rows.Add(dr);

        } 

           Document doc = pdfWorker.readyDocument();
        pdfWorker.createTable(doc, dt);

        String filePath = Server.MapPath("~/reports/files/");          
        String fileName = "report_" + DateTime.Now.ToString("MM-dd-yyyy") + ".pdf";
        filePath += fileName;
        pdfWorker.savePDF(doc, filePath);
        Response.ContentType = "application/pdf";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.TransmitFile(filePath);
        Response.End();
        }

    protected void generateReport(object sender, EventArgs e)
    {
        int[] selectedLocations = getLocations();
        int[] selectedItemTypes = getItems();
        DateTime from = Convert.ToDateTime(fromDateBox.Text);
        DateTime to = Convert.ToDateTime(toDateBox.Text);


        if (!allButton.Checked)
        {
            Int32 statusID;
            if (openButton.Checked)
            {
                statusID = 1;
            }
            else
            {
                statusID = 2;
            }

            using (ticketModel dbContext = new ticketModel())
            {
                allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
                allTicketGrid.DataBind();
            }

        }
        else
        {

            using (ticketModel dbContext = new ticketModel())
            {
                allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
                allTicketGrid.DataBind();
            }

        }


    }

和我的pdfWorker类:​​

   static class pdfWorker
    {
           public static Document readyDocument() {
        Document doc = new Document();
        Section section = doc.AddSection();
        Style docStyles = doc.Styles["Normal"];
        docStyles.Document.DefaultPageSetup.Orientation = MigraDoc.DocumentObjectModel.Orientation.Landscape;
        docStyles.Font.Size = 8;
               docStyles.ParagraphFormat.FirstLineIndent = 0;

        return doc;
        }

        public static void createTable(Document document, DataTable dataTable)
        {
            Table table = new Table();
            table.Format.Font.Size = 6;
            table.BottomPadding = 10;

            int colCount = dataTable.Columns.Count;
            Row pdfRow;
            Cell pdfCell;



          for (int i = 0; i < colCount; i++)
                {
                    table.AddColumn();

                }

          pdfRow = table.AddRow();
          for (int i = 0; i < colCount; i++)
          {


              pdfCell = pdfRow.Cells[i];
              pdfCell.Row.Format.Font.Size = 10;
              pdfCell.AddParagraph(dataTable.Columns[i].ToString());

          }

            foreach (DataRow row in dataTable.Rows)
            {

                 pdfRow = table.AddRow();
                 pdfRow.HeightRule = RowHeightRule.AtLeast;
                for (int i = 0; i < colCount; i++)
                {

                    pdfCell = pdfRow.Cells[i];
                    pdfCell.AddParagraph(row[i].ToString());


                }
            }

            document.LastSection.Add(table);
        }

              public static void savePDF(Document doc, String fileName) {
                PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
                SaveFileDialog saveDialog = new SaveFileDialog();

                      renderer.Document = doc;
                      renderer.RenderDocument();
                      renderer.PdfDocument.Save(fileName);




            }


        }

    }

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以将填充GridView的代码放在一个单独的方法中:

protected void generateReport(object sender, EventArgs e)
{
    BindReportData();
}

private void BindReportData()
{
    int[] selectedLocations = getLocations();
    int[] selectedItemTypes = getItems();
    DateTime from = Convert.ToDateTime(fromDateBox.Text);
    DateTime to = Convert.ToDateTime(toDateBox.Text);

    if (!allButton.Checked)
    {
        Int32 statusID;
        if (openButton.Checked)
        {
            statusID = 1;
        }
        else
        {
            statusID = 2;
        }

        using (ticketModel dbContext = new ticketModel())
        {
            allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
            allTicketGrid.DataBind();
        }
    }
    else
    {
        using (ticketModel dbContext = new ticketModel())
        {
            allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
            allTicketGrid.DataBind();
        }
    }
}

exportReport

的开头调用该方法
protected void exportReport(object sender, EventArgs e)
{
    BindReportData();
    ...
}