Which a better way to print in asp.net vb.net? - asp.net

I want to print a gridview and a labels in header and label in footer ( after the gridview populated )
to use CrystalReports or window.print
or anything else that make my goal achived ( specialy something that easy to use )

Easiest way is to export the datagrid, download and print from Excel.
Dim dg As System.Web.UI.WebControls.DataGrid 'For example if your grid was called dg
Dim reportTitle As String = "Add A Title - Since DataGrid Doesn't Have One"
'export to excel
context.Response.Buffer = True
context.Response.ClearContent()
context.Response.ClearHeaders()
context.Response.ContentType = "application/vnd.ms-excel"
EnableViewState = True
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
dg.RenderControl(hw) '<-- built-in Method of all System.Web.UI.Control objects
Context.Response.Write("<b><center><font size=3 face=Verdana color=#0000FF>" & reportTitle & "</font></center></b>")
Context.Response.Write(tw.ToString())
Context.Response.Flush()
Context.Response.Close()
Context.Response.End()
For more info, you can check the Microsoft docs https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.control.rendercontrol

Related

Export to excel on asp.net

I want to export to excel, but I want to choose the excel file that has the customized coloring and modification instead of the default excel page. How can I achieve this on asp.net with vb.
Take a look also on EasyXLS library. For exporting to excel, you can start with this code sample:
http://www.easyxls.com/manual/FAQ/export-to-excel-in-dot-net.html
Try using specific libraries for export to excel in asp.net. For example exist Syncfusion XlsIo, Telerik or spreadsheetgear (This is specializing in excel). In my case I'm using Syncfusion XlsIo and with this customize all the reports in excel, also can use graphics and conditional formats
Public Sub ExportToExcel (dt As DataTable)
If dt.Rows.Count > 0 Then
Dim filename As String = "DownloadMobileNoExcel.xls"
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim dgGrid As New DataGrid()
dgGrid.DataSource = dt
dgGrid.DataBind()
'Get the HTML for the control.
dgGrid.RenderControl(hw)
'Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", (Convert.ToString("attachment; filename=") & filename) + "")
Me.EnableViewState = False
Response.Write(tw.ToString())
Response.End()
End If
End Sub

Vb.net export gridview to excel

I am having trouble exporting my gridview to an excel file. Everything works except when I hit the export button, the data that is supposed to be exported to an excel file displays on the web page instead. I am suspecting that this is a problem with Response.ContentType and the file name that I specified. However, I already went through multiple documentations and examples and it doesn't seem like those two are the root problems in my case. Can Anyone help?
<asp:Button ID="btnExport" runat="server" Text="Export To MS Excel File" CssClass="btnMain" OnClick="btnExport_Click" />
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim filename As String = "PerformanceEval Status Report" & Date.Now.Year.ToString & "-" & _
formatNumberTo2Digits(DateTime.Now.Month) & "-" & formatNumberTo2Digits(DateTime.Now.Day) & ".xls"
With Page.Response
.Clear()
.Buffer = True
.AddHeader("content_disposition", "attachment;filename" & filename)
.Charset = ""
'--to open the Excel file without saving then comment out the line below
'.Cache.SetCacheability(HttpCacheability.NoCache)
'.ContentType = "application/vnd.xls" 'data appears on web page
'.ContentType = "application/vnd.ms-excel" 'try to download .aspx document NOT .xml
.ContentType = "application/ms-excel" 'data appears on web page
End With
Dim strWriter As New System.IO.StringWriter
Dim htmlWriter As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(strWriter)
Dim gvexport As GridView = New GridView
gvexport.AutoGenerateColumns = False
gvexport.CssClass = "gridData"
gvexport.GridLines = GridLines.Horizontal
gvexport.HeaderStyle.CssClass = "gridHeader"
gvexport.RowStyle.CssClass = "gridRow"
gvexport.AlternatingRowStyle.CssClass = "gridRow_Alt"
gvexport.FooterStyle.CssClass = "gridFooter"
Dim dv As DataView = New DataView(Me.ds.Tables(0)) 'default is sorted by last name
'Dim dv As DataView = New DataView(Me.ds.Tables(0))
dv.RowFilter = GetFilter()
'-- add columns for report
addGVcolumn("Employee Name", "EmployeeName", gvexport, -1, HorizontalAlign.Left)
addGVcolumn("Employee ID", "SID", gvexport, -1, HorizontalAlign.Left)
addGVcolumn("Email", "WorkEmail", gvexport, -1, HorizontalAlign.Left)
addGVcolumn("StatusID", "StatusID", gvexport, 50, HorizontalAlign.Center)
gvexport.DataSource = dv
gvexport.DataBind()
gvexport.RenderControl(htmlWriter)
Response.Output.Write(strWriter.ToString())
Response.Flush()
Response.End()
Again, I am able to generate the content but is not able to make my data exports into excel. Thanks a lot!
You are giving the wrong header:
.AddHeader "content-disposition", "attachment; filename="& filename &";"

Is it possible to export a sql table to excel using asp.net

I have a webpage with an export button. Is it possible to export a sql table to excel when this button is pressed? I can do it with a gridview but would just like a simple button with code behind to do the work. Can someone point me in the direction I need?
Here is a utility function you can use:
Public Shared Sub ExportToSpreadsheet(table As DataTable, filename As String)
' Get a hold of the HTTP context and clear it, because we are going to push the CSV data through the context
Dim context = HttpContext.Current
context.Response.Clear()
' Loop through each column in your data table
For Each column As DataColumn In table.Columns
' Write column names
context.Response.Write(column.ColumnName + ";")
Next
context.Response.Write(Environment.NewLine)
' Loop through each row in the data table
For Each row As DataRow In table.Rows
' Loop through each column in row
For i As Integer = 0 To table.Columns.Count - 1
' Write each column value
context.Response.Write(row(i).ToString().Replace(";", [String].Empty) & ";")
Next
' Write a new line between rows of data
context.Response.Write(Environment.NewLine)
Next
' Set the content type and headers
context.Response.ContentType = "text/csv"
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" & filename & ".csv")
context.Response.[End]()
End Sub
Then you can call it like this:
ExportToSpreadsheet(YourDataTable, "YourFileName")
Note: Since it is a Shared function, then you can put it in a utility class and do not need to instantiate (New) the class to use the function.
If you want it in excel you can use the following code. Select the data and put it in a Gridview and do the following.
Dim GridView1 As New GridView
SqlDataSource1.SelectCommand = "SELECT * FROM TableName"
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim oStringWriter As New System.IO.StringWriter
Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
GridView1.RenderControl(oHtmlTextWriter)
Response.Write(oStringWriter.ToString())
Response.End()
You can also format the Gridview to make it look good on the Excel Sheet.

a ButtonField within DataGrid calling Vb.net as Javascript.... for streaming PDF?

I just noticed it last night,
Anyway, let's get to the interesting case here.
I have a ButtonField within DataGrid, and if you notice it here...
The Interface of that ButtonField is looks like a LINK.
But if we hover on it, it appeared as Javascript's call.
Here is the Image ScreenShot
Ya, that's the 1st case.
IT IS a javascript's call.
I didnt notice about it lately. (hehehe).
Then, if we click on that... it would call the createPDF() function. The function behind the scene (which I'm using VB.net) is to execute these code;
Protected Sub createPDF()
Dim document As New Document()
Dim mem As LengthFixingStream = New LengthFixingStream()
' instantiate a iTextSharp.text.pdf.Document
'Dim mem As New MemoryStream()
' PDF data will be written here
PdfWriter.GetInstance(document, mem)
' tie a PdfWriter instance to the stream
document.Open()
Dim titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD)
document.Add(New Paragraph("Northwind Traders Receipt", titleFont))
document.Close()
' automatically closes the attached MemoryStream
Dim docData As Byte() = mem.GetBuffer()
' get the generated PDF as raw data
' write the document data to response stream and set appropriate headers:
Response.AppendHeader("Content-Disposition", "attachment; filename=testdoc.pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(docData)
Response.[End]()
End Sub
But somehow... this of course would not deliver the PDF into the browser.
BEcause It's called by Javascript, nor the direct as Hyperlink (normally).
Thus, I'm wondering could we get the ASP.net Call new Window,
and then redirect the createPDF() result into it?
Correct me if i'm wrong...
Here is just some mockup so you get the idea. I haven't tested this. Basically you will have to put the above code in a new page...say "receipt.aspx" and execute it on the load event...you will need to setup an id parameter...if data is being pulled from the db to generate the pdf.
on the button click add the following
Dim sb As New System.Text.StringBuilder()
sb.Append("<script language='javascript'>")
sb.Append("window.open('receipt.aspx.htm?id=123'', 'Receipt',")
sb.Append("'width=800, height=800, menubar=yes, resizable=no');<")
sb.Append("/script>")
Dim t As Type = Me.GetType()
If Not ClientScript.IsStartUpScriptRegistered(t, "PopupScript") Then
ClientScript.RegisterStartUpScript(t, "PopupScript", sb.ToString())
End If
Notice the "id=123" querystring value I am passing to receipt.aspx?
You can then call that in the receipt.aspx page like this
Dim id as String = Request.QueryString("id")
CreatePDF(id)
...shoot! Just realized you are using a Grid...the principle remains the same, just wireup the buttons on RowDataBound event.
Protected Sub GridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim Id As String = DirectCast(e.Row.Cells(0).FindControl("quotationid"), Label).Text
Dim myButton As New Button
myButton = DirectCast(e.Row.Cells(4).FindControl("btnViewReceipt"), Button)
myButton.Attributes.Add("OnClick", "window.open('receipt.aspx?id=" + id + "','Receipt','scrollbars=yes','width=800,height=800')")
End If
End Sub

How do I use id's of HTML elements in another sub when they are created from server-side code?

I have a table that I'm creating in code behind with the final column containing a HTML checkbox with runat="server".
The code I'm using to do this is:
Do While reader.HasRows
Do While reader.Read
Dim tNewRow As New HtmlTableRow
Dim cellSKU, cellDESCR, cellDept1, cellDeptGrp1, cellDeptRng1, cellStand, cellBoard, cellSelect As New HtmlTableCell
cellSKU.InnerHtml = "<a href='edit.aspx?edit=" & reader("SKUN") & "'>" & reader("SKUN") & "</a>"
cellDESCR.InnerText = reader("DESCR")
cellDept1.InnerText = reader("DPT1")
cellDeptGrp1.InnerText = reader("GRP1")
cellDeptRng1.InnerText = reader("RNG1")
cellBoard.InnerText = reader("BOARD")
cellStand.InnerText = reader("STAND")
cellSelect.InnerHtml = "<input type='checkbox' id='selectedSKU' value='" & reader("SKUN") & "' runat='server' />"
tNewRow.Cells.Add(cellSKU)
tNewRow.Cells.Add(cellDESCR)
tNewRow.Cells.Add(cellDept1)
tNewRow.Cells.Add(cellDeptGrp1)
tNewRow.Cells.Add(cellDeptRng1)
tNewRow.Cells.Add(cellStand)
tNewRow.Cells.Add(cellBoard)
tNewRow.Cells.Add(cellSelect)
tNewRow.Style.Add("border", "solid 1px #cccccc")
skusTable.Rows.Add(tNewRow)
Loop
reader.NextResult()
Loop
But I want to use the checkbox in another sub such as:
Protected Sub editSkus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles editSkus.Click
End Sub
Though I can't use selectedSKU.whatever as the checkbox doesn't exist on the page until the other section of code is run.
Is there a way I can get around this or another way of doing things?
Thanks in advance for any help.
It's nasty, but here goes...
Dim skusTable As New HtmlTable
Dim i As Integer
Do While reader.HasRows
Do While reader.Read
i = i + 1
Dim tNewRow As New HtmlTableRow
tNewRow.ID = "MyRow" & i
Dim cellSKU, cellDESCR, cellDept1, cellDeptGrp1, cellDeptRng1, cellStand, cellBoard, cellSelect As New HtmlTableCell
cellSKU.InnerHtml = "<a href='edit.aspx?edit=" & reader("SKUN") & "'>" & reader("SKUN") & "</a>"
cellDESCR.InnerText = reader("DESCR")
cellDept1.InnerText = reader("DPT1")
cellDeptGrp1.InnerText = reader("GRP1")
cellDeptRng1.InnerText = reader("RNG1")
cellBoard.InnerText = reader("BOARD")
cellStand.InnerText = reader("STAND")
'Create the checkbox as a webcontrol and add it to the table cell
Dim checkBox As New HtmlControls.HtmlInputCheckBox
checkBox.Value = reader("SKUN")
checkBox.ID = "selectedSKU"
cellSelect.ID = "SelectedCell"
cellSelect.Controls.Add(New WebControls.CheckBox)
tNewRow.Cells.Add(cellSKU)
tNewRow.Cells.Add(cellDESCR)
tNewRow.Cells.Add(cellDept1)
tNewRow.Cells.Add(cellDeptGrp1)
tNewRow.Cells.Add(cellDeptRng1)
tNewRow.Cells.Add(cellStand)
tNewRow.Cells.Add(cellBoard)
tNewRow.Cells.Add(cellSelect)
tNewRow.Style.Add("border", "solid 1px #cccccc")
skusTable.Rows.Add(tNewRow)
Loop
reader.NextResult()
Loop
Now all you need do is use FindControls to get to the element...
Dim myRow As HtmlControls.HtmlTableRow = skusTable.FindControl("MyRow" & i)
'Probably be good to check the object exists first....
If Not myRow Is Nothing Then
Dim myCell As HtmlControls.HtmlTableCell = myRow.FindControl("SelectedCell")
If Not myCell Is Nothing Then
Dim myCheckbox As HtmlControls.HtmlInputCheckBox = myCell.FindControl("selectedSKU")
If Not myCheckbox Is Nothing Then
'Got it! now is it selected?
Return myCheckbox.Checked
End If
End If
End If
The runat="Server" attribute is parsed by the ASP.NET process and indicates that it should create some kind of control object. At the point your code is running this parsing has already been done. ASP.NET does not parse content added to the InnerHTML property to look for additional runat attributes or any other ASP.NET specific markup, InnerHTML is expected to be strictly standard HTML that is to be sent to the server.
You could create an instance of the CheckBox ASP.NET control and add it to the cellSelect controls collection, which is the equivalent to runat="Server". However that doesn't really help because you want to bind an event to this control but on post back this control will no longer exist.
Is there a reason you are not using DataGrid to acheive this UI?

Resources