Printing Primer

Get the Help You Need

Josef Finsel

October 30, 2009

5 Min Read
ITPro Today logo

asp:Q&A

LANGUAGES:VB.NET

ASP.NET VERSIONS:1.x

 

Printing Primer

Get the Help You Need

 

By Josef Finsel

 

This month s column is one that has a simple answer and acomplex answer, depending on how you want to handle it.

Q: Is there a fairlyeasy way to print a Web form in VB.net (http://vb.net) using a Print button? I ammodifying someone else s program and I would like to add a Print button to an ASPWeb form. I intend to use an onClick event to make the Print button invisible(either in JavaScript or code-behind) during the print process, and then, Ithink, handle the printing itself in the code-behind.

 

A: The short answer to this is to add a button with a verysmall snippet of JavaScript code that says:

 

window.print

 

That command, the equivalent of selecting File | Print,opens the printer dialog box to allow the user to select where they want it to print.But there are problems with this; the most notable one being that Web pages don talways translate well into printed objects. For instance, take a multi-linetext box. It s easy to fill the text box with text that causes some of the textto scroll out of site. When you print that Web page, the printout will showonly as much text as you see displayed in the Web page.

 

To get around this, a Print button usually opens up a newwindow with the data formatted for printing. And that s just what we re goingto do this month, beginning with the BasicForm.aspx form (available for download;see end of article for details).

 

BasicForm.aspx is a simple form with several differentinputs: a couple of TextBoxes, a DropDownList, a multi-line TextBox, aRadioButtonList, and a CheckBoxList. This variety will cover just abouteverything necessary to build upon the code we re going to use to store thevalues and open up a printable form. This is all handled through theSaveControlInfo procedure, called by the Print button on the SaveControlInfo(Me.Controls)form (see Figure 1).

 

Private Sub SaveControlInfo(ByVal ctls As ControlCollection)

 Dim ctl As Control

 For Each ctl In ctls

   If ctl.HasControls Then

     Select Casectl.GetType.ToString

       Case"System.Web.UI.WebControls.CheckBoxList"

           Dim x AsSystem.Web.UI.WebControls.CheckBoxList

           x = ctl

           Dim li AsListItem

           Dim s As String

           For Each li Inx.items

               Ifli.Selected = True Then

                   s = s& li.Text & "
"

               End If

           Next

           Session.Add(ctl.ID, s)

       Case Else

           SaveControlInfo(ctl.Controls)

     End Select

   Else

     If ctl.ID <>"" Then

       Select Casectl.GetType.ToString

           Case"System.Web.UI.WebControls.TextBox"

               Dim x AsSystem.Web.UI.WebControls.TextBox

               x = ctl

               Dim s AsString

               s = x.Text

               s =s.Replace(Chr(10), "
")

               Session.Add(ctl.ID, s)

           Case"System.Web.UI.WebControls.DropDownList"

               Dim x AsSystem.Web.UI.WebControls.DropDownList

               x = ctl

               Session.Add(ctl.ID, x.SelectedValue)

           Case"System.Web.UI.WebControls.RadioButtonList"

               Dim x AsSystem.Web.UI.WebControls.RadioButtonList

               x = ctl

               Session.Add(ctl.ID, x.SelectedValue)

           Case"System.Web.UI.WebControls.CheckBox"

               Dim x AsSystem.Web.UI.WebControls.CheckBox

               x = ctl

               Ifx.Checked Then

                   Session.Add(ctl.ID,x.Text)

               End If

           Case Else

               Session.Add(ctl.ID, ctl.GetType.ToString())

       End Select

     End If

   End If

 Next

End Sub

Figure 1:SaveControlInfo is a recursive function designed to put data from controls on aform into session variables.

 

SaveControlInfo is fairly straightforward. It cyclesthrough the controls and determines what needs to be done based on the type ofcontrol based on a Select Case statement. Although the Select Case statementprovides cleaner code to read and debug than a large number of If Then/Else Ifstatements, it precludes the use of GetType(control), which requires Is after it.Therefore, it is necessary to use the string description returned bycontrol.GetType.ToString. In the simplest type of controls, a DropDownList forexample, all that is required is creating a variable of the appropriate controltype and then getting the selected value and storing it into the sessionvariable with the Id of the control.

 

There are a couple of things that need to be addressed forsome controls. For instance, multi-line TextBoxes are a good example. If theuser has entered a carriage return/line feed in the box to separate aparagraph, this will not show up when the text is displayed in a literal tag.Instead, HTML will treat the carriage return/line feed as white space and skipover it. Therefore, I m doing a quick replace of all the line feeds in the textwith the
element to provide a line break. Similarly, the CheckBoxListpotentially requires displaying multiple items, which I am separating with the
tag.

 

Now we come to the second interesting problem: ASP.NET hasno way to open a new window to display the form we want to print. ASP.NET isserver side; it doesn t interact with the browser directly enough to open apopup window. JavaScript contains a window.open command that suits our needsperfectly. The question is, how do we get it to fireon command. The answer to that can be found in the Page object. There are twomethods of the Page object that we can use: Page.RegisterStartupScript andPage.RegisterClientScriptBlock. Page.RegisterStartupScript adds a script thatwill execute as soon as the page is posted back. Page.RegisterClientScriptBlockallows you to register code and link it to the client-side event of anothercontrol. In this case, we ll use Page.RegisterStartupScript and just add it tothe Print button s Click event following the call to SaveControlInfo. Figure 2shows the whole code to load the session data and then pop up the window toprint.

 

Private Sub Print_Click(ByVal sender As System.Object, _ &

 ByVal e AsSystem.EventArgs) Handles Print.Click

 'Save data to sessionvariables

 SaveControlInfo(Me.Controls)

 Dim popupScript As String= "                 "window.open('PrintForm.aspx','_blank', " & _                 "'menubar=yes, resizable=yes,scrollbar=yes')" & _                 ""

 Page.RegisterStartupScript("PopupScript", popupScript)

End Sub

Figure 2: Save thevalues to a session variable and open up a popup window from which to print.

 

Finally, we get to PrintForm.aspx. This simple formretrieves data from the session, populates a form, displays it, then prints itby using a script block in the body element:

 

 

Now that you understand the basics, this could easily beexpanded upon to provide a generic class that would store all the data in aform and print it out. That would require adding a way to store the labels andthe order in which they appear, but then the print page could easily pull themout of the session, build the table on the fly, and print it. I ll leave thatas an exercise for you.

 

That wraps up this month s column. Send your ASP.NETquestions to [email protected] I can help you get the answers you need.

 

The sample code accompanyingthis article is available for download.

 

Josef Finsel is asoftware consultant. He has published a number of VB and SQL Server-relatedarticles and is currently working on the syntax for FizzBin.NET, a programminglanguage that works the way programmers have always suspected. He s also authorof The Handbook for Reluctant DatabaseAdministrators (Apress, 2001).

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like