KellyM
KellyM

Reputation: 2522

ASP.NET - Retrieving Grid View Data when EnableViewState is Set to False

I am building an application that needs to display data in a GridView control, grouped by a particular value, and then export it to PDF.I used this set of classes here (http://www.agrinei.com/gridviewhelper/gridviewhelper_pt.htm) for grouping, and it works well. However, I had to set EnableViewState to false for it to work properly. The problem comes when I need to export it to PDF. Previously (before using GridViewHelper), this was working. However, it now generates an empty report (I suppose because EnableViewState is false).

How can I save the data and structure of the GridView produced through use of the GridViewHelper class in order to export it to PDF?

Some of my aspx (portions of code omitted for brevity)

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();
            }

        }


    }

and my pdfWorker class:

   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);




            }


        }

    }

Thanks so much for any help.

Upvotes: 0

Views: 281

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

You can put the code that populates the GridView in a separate method:

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();
        }
    }
}

And call that method at the start of exportReport:

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

Upvotes: 1

Related Questions