2011-02-27 15 views
5

Estoy utilizando Visual Studio 2008 y SQL Server 2008cuadrícula de impresión con mesa en asp.net

Quiero imprimir mi "gridview con mesa" usando un botón en asp.net 3.5 código tiene tres partes por primera vez este es de mi página por defecto

protected void btnPrint_Click(object sender, EventArgs e) 
{ 
    Session["ctrl"] = Panel1; 
    ClientScript.RegisterStartupScript(this.GetType(), "onclick", 
     "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>"); 
    PrintHelper.PrintWebControl(Panel1); 
} 

el código de la página de impresión de este

protected void Page_Load(object sender, EventArgs e) 
{ 
    Control ctrl = (Control)Session["ctrl"]; 
    PrintHelper.PrintWebControl(ctrl); 
} 

y esta es mi impresión clase de ayuda

public PrintHelper() 
{ 
} 

public static void PrintWebControl(Control ctrl) 
{ 
    PrintWebControl(ctrl, string.Empty); 
} 

public static void PrintWebControl(Control ctrl, string Script) 
{ 
    StringWriter stringWrite = new StringWriter(); 
    System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); 
    if (ctrl is WebControl) 
    { 
     Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w; 
    } 
    Page pg = new Page(); 
    pg.EnableEventValidation = false; 
    if (Script != string.Empty) 
    { 
     pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script); 
    } 
    HtmlForm frm = new HtmlForm(); 
    pg.Controls.Add(frm); 
    frm.Attributes.Add("runat", "server"); 
    frm.Controls.Add(ctrl); 
    pg.DesignerInitialize(); 
    pg.RenderControl(htmlWrite); 
    string strHTML = stringWrite.ToString(); 
    HttpContext.Current.Response.Clear(); 
    HttpContext.Current.Response.Write(strHTML); 
    HttpContext.Current.Response.Write("<script>window.print();</script>"); 
    HttpContext.Current.Response.End(); 
} 

favor me ayude a cabo

+0

esta pregunta es demasiado vaga. más detalles necesarios: dónde, qué ... – onof

+0

he creado una página web que imprime mi vista de cuadrícula que muestra los datos en gridview pero el problema es que no me muestra las filas y columnas de la vista de cuadrícula – CHANDRAHAS

+0

¿Puede mostrarnos el código que tienes hasta ahora, así que no estamos adivinando? – RQDQ

Respuesta

1

Crear un adaptador de datos, crear un objeto de comando con una consulta de selección, establece el mandato del adaptador a este objeto de mandatos, emita un adaptador. fill (conjunto de datos), establezca el origen de datos de gridview como el conjunto de datos y el enlace de datos GridView.

Para el código, una simple búsqueda en Google funcionará. Ni siquiera especificaste un idioma. Supongo que estás trabajando en C# y este es tu proyecto universitario. ¿Lo es?

+0

sí, es un proyecto de banca en línea, quiero imprimir el estado del banco, pero no quiero usar el informe de cristal; mi fuente de datos funciona bien; la base de datos es que quiero que la tabla y la fila se vean en la página impresa. – CHANDRAHAS

+0

En ese caso, cree una nueva funcionalidad de impresión y úselo para redireccionar a una página con solo la Vista de cuadrícula. Si ha visto suficientes sitios web bancarios, verá que los bancos generalmente lo colocan en un JavaScript y abre una nueva ventana emergente con solo la tabla gridview y un botón de impresión. Especialmente, el sitio web ferroviario indio. En cualquier momento, debe considerar Crystal Reports ya que es una nueva característica en .NET y agregará un valor considerable a su proyecto. – r3st0r3

1

Primero, visualice sus datos en el GridView (hay aproximadamente un bazillion de recursos en este sitio y otros para mostrarle cómo hacerlo).

Aquí está el javascript para imprimir la ventana:

<INPUT TYPE="button" onClick="window.print()"> 
+0

pero esto imprimirá toda la página solo necesito que se imprima mi gridview de datos – CHANDRAHAS

+1

Luego tendrá que hacer una página que solo tenga su gridview de datos. – RQDQ

2

tal vez esto puede ayudar.

GridViewExportUtil public class {

public static void Export(string fileName, GridView gv) 
    { 
     HttpContext.Current.Response.Clear(); 
     HttpContext.Current.Response.ClearHeaders(); 
     HttpContext.Current.Response.ClearContent(); 
     HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254"); 
     HttpContext.Current.Response.Charset = "windows-1254"; //ISO-8859-13 ISO-8859-9 windows-1254 

     HttpContext.Current.Response.AddHeader(
      "content-disposition", string.Format("attachment; filename={0}", fileName)); 
     HttpContext.Current.Response.ContentType = "application/ms-excel"; 
     string header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title></title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1254\" />\n<style>\n</style>\n</head>\n<body>\n"; 

     using (StringWriter sw = new StringWriter()) 
     { 
      using (HtmlTextWriter htw = new HtmlTextWriter(sw)) 
      { 
       // Create a form to contain the grid 
       Table table = new Table(); 
       table.GridLines = GridLines.Horizontal; 
       //table.CellSpacing = 17; 

       // add the header row to the table 
       if (gv.HeaderRow != null) 
       { 
        GridViewExportUtil.PrepareControlForExport(gv.HeaderRow); 
        table.Rows.Add(gv.HeaderRow); 
       } 

       // add each of the data rows to the table 
       foreach (GridViewRow row in gv.Rows) 
       { 
        GridViewExportUtil.PrepareControlForExport(row); 
        table.Rows.Add(row); 
       } 

       // add the footer row to the table 
       if (gv.FooterRow != null) 
       { 
        GridViewExportUtil.PrepareControlForExport(gv.FooterRow); 

        table.Rows.Add(gv.FooterRow); 
        //table.Height = 17; 
       } 

       // render the table into the htmlwriter 
       table.RenderControl(htw); 

       // render the htmlwriter into the response 
       HttpContext.Current.Response.Write(header + sw.ToString()); 
       HttpContext.Current.Response.End(); 
      } 
     } 
    } 

    /// <summary> 
    /// Replace any of the contained controls with literals 
    /// </summary> 
    /// <param name="control"></param> 
    private static void PrepareControlForExport(Control control) 
    { 
     for (int i = 0; i < control.Controls.Count; i++) 
     { 
      Control current = control.Controls[i]; 
      if (current is LinkButton) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); 
      } 
      else if (current is ImageButton) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); 
      } 
      else if (current is HyperLink) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); 
      } 
      else if (current is DropDownList) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); 
      } 
      else if (current is CheckBox) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); 
      } 
      else if (current is Label) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as Label).Text)); 
      } 

      if (current.HasControls()) 
      { 
       GridViewExportUtil.PrepareControlForExport(current); 
      } 
     } 
    } 
} 
Cuestiones relacionadas