Error when wanting to pass a gridview to an excel file

0

I have my gridview defined as well

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" DataSourceID="SqlDataSource1" Width="976px">
        </asp:GridView>

and I'm trying to pass the data to an excel in the following way

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridView1.DataBind();
            }

        }

protected void Button2_Click(object sender, EventArgs e)
        {
            ExportToExcel("Informe.xls", GridView1);
        }


        private void ExportToExcel(string nameReport, GridView wControl)
        {
            HttpResponse response = Response;
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            Page pageToRender = new Page();
            HtmlForm form = new HtmlForm();
            form.Controls.Add(wControl);
            pageToRender.Controls.Add(form);
            response.Clear();
            response.Buffer = true;
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=" + nameReport);
            response.Charset = "UTF-8";
            response.ContentEncoding = Encoding.Default;
            pageToRender.RenderControl(htw);
            response.Write(sw.ToString());
            response.End();
        }

in a computer where I made the first tests works perfect but now in the new computer it shows the following error with the method

  

pageToRender.RenderControl (htw);

Exception thrown: 'System.Web.HttpException' in System.Web.dll

    Additional information: Control 'GridView1_ctl11' of type 'DataControlPagerLinkButton' must be placed inside a form tag with runat=server.

and I've already tried many things and I can not find the solution

    
asked by Sebastian Mateus Villegas 23.11.2016 в 06:29
source

3 answers

1

You could add the EnableEventValidation="false" condition in the <% @ Page part of your page where the information is to be exported.

Try it and tell me what the result is.

Greetings.

    
answered by 25.11.2016 / 20:06
source
0

The error comes from calling pageToRender.RenderControl(htw); , so the page generates an exception since the control is being generated outside of a form.

One solution is to avoid this exception by overwriting VerifyRenderingInServerForm this way:

public override void VerifyRenderingInServerForm(Control control)
{
}
    
answered by 23.11.2016 в 09:06
0

Dear, I export in the same way that you do the data of a gridview to excel, I recommend that if you want to export everything you show in the grid and you will not modify data that is in it and only place a button to export this should be useful for you:

protected void btnExportarPendientes_Click(object sender, ImageClickEventArgs e)
{
    string nombreArchivo = "Rep_Fic_Pend_Despacho.xls";
    List<saapt010> listDatos = new List<saapt010>();
    listDatos = BuscarPendientes();
    DataGrid dg = new DataGrid();
    dg.AllowPaging = false;
    dg.DataSource = listDatos;
    dg.DataBind();

    System.Web.HttpContext.Current.Response.Clear();
    System.Web.HttpContext.Current.Response.Buffer = true;
    System.Web.HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
    System.Web.HttpContext.Current.Response.BinaryWrite(Encoding.UTF8.GetPreamble());
    System.Web.HttpContext.Current.Response.Charset = "";
    System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
      "attachment; filename=" + nombreArchivo);

    System.Web.HttpContext.Current.Response.ContentType =
      "application/vnd.ms-excel";
    System.IO.StringWriter stringWriter = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlTextWriter =
      new System.Web.UI.HtmlTextWriter(stringWriter);
    dg.RenderControl(htmlTextWriter);
    System.Web.HttpContext.Current.Response.Write(stringWriter.ToString());
    System.Web.HttpContext.Current.Response.End();
}




protected List<saapt010> BuscarPendientes()
{
    List<saapt010> listDatos = new List<saapt010>();
    string script = String.Empty;
    string consulta = String.Empty;
    DateTime fecha = DateTime.Now;

    string conexion = ConfigurationManager.ConnectionStrings["samConnectionString"].ConnectionString;
    IfxConnection conn = new IfxConnection(conexion);
    conn.Open();
    try
    {
        consulta = ViewState["ConsultaPendientes"].ToString();
        IfxCommand cmd = new IfxCommand(consulta, conn);
        cmd.Parameters.Add("fechaUno", IfxType.DateTime).Value = Convert.ToDateTime(ViewState["FechaUnoPen"].ToString());
        cmd.Parameters.Add("fechaDos", IfxType.DateTime).Value = Convert.ToDateTime(ViewState["FechaDosPen"].ToString());
        IfxDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            saapt010 saap = new saapt010();
            if (reader.GetString(1) != "")
            {
                saap.Rut = reader.GetString(1) + "-" + reader.GetString(2);
            }
            else
            {
                saap.Rut = "";
            }
            saap.Fecha = reader.GetDateTime(4).ToString("dd-MM-yyyy");
            saap.NumeroBio = reader.GetString(5);
            saap.Nombre = reader.GetString(6) + " " + reader.GetString(7) + " " + reader.GetString(8);
            saap.ServicioOrigen = reader.GetString(13);
            saap.MedicoOri = reader.GetString(14);
            saap.Prevision = reader.GetString(10);
            saap.Nmuestras = reader.GetString(12);
            if (reader.GetString(16) != "null")
            {
                saap.Supervisor = reader.GetString(16);
            }
            else
            {
                saap.Supervisor = String.Empty;
            }
            if (reader.GetString(15) != "")
            {
                fecha = Convert.ToDateTime(reader.GetString(15));
                saap.FechaDesp = fecha.ToString("dd-MM-yyyy");
            }
            else
            {
                saap.FechaDesp = String.Empty;
            }

            listDatos.Add(saap);
        }
    }
    catch (Exception ex)
    {
        script = "alert('Se ha producido un error al cambiar de página en el modulo de busqueda por pendientes de despacho. Favor comuniquese con el área de informática');";
        ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true);
    }
    return listDatos;
}

If you notice, I create a variable of type List < > where I keep all the data of the grid and this is the return in the function to look for slopes that is my case. later I create a datagrid and this datagrid I assign the List < > with the data of my grid and ready. Anything you tell me and put the code to help you more.

Greetings

    
answered by 25.11.2016 в 19:34