Today I was given the task of creating a textbox control that contained text from an external text file from the Legal Department. It was for one of those pages I’m sure everyone has seen at some point where you have to read the “Acceptance Agreement” and check the box before you can view another web page or download a file. Below are the steps and the code necessary to complete the task.
- Create a web page named “LegalAgreement.aspx”.
- Add a textbox control and edit the properties: ID=”txtLegalAgreement” TextMode=”MultiLine” Width=”80%” Height=”100px”
- Add a checkbox control and edit the properties: ID=”ckAgree” Text=”I accept” AutoPostBack=”True”
- Add a button control and edit the properties: ID=”btnSubmitAgreement” Text=”View Documents”
- Add code-behind in VB.NET for a Stream Reader to open the textfile and place the contents inside of the textbox control.
VB.NET CODE -At the very top of the class file add:
“Imports System.IO” Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ‘open file for reading Dim myLegalText As String = Server.MapPath(”LegalAgreement.txt”) ‘Get streamReader class that can be used to read the file. Dim objStreamReader As StreamReader objStreamReader = File.OpenText(myLegalText) 'Now, read the entire file into a streams Dim contents As String = objStreamReader.ReadToEnd( ) ‘Set the test of the file to a web control txtLegalAgreement.Text = contents ‘Close the StreamReader objStreamReader.Close( ) End Sub
Add code for the button to assign a Session Variable and Re-direct to the next page. -Inside the class file add a variable at the top of the page.
Inherits System.Web.UI.Page Dim sessionLegal As String = “” Protected Sub btnSubmitAgreement_Click(ByVal sender As Object, ByVal e As System.EventArgs)Handles btnSubmitAgreement.Click If ckAgree.Checked Then ’set the session variable AGREED Session(”sessionLegal”) = “LEGALACCEPTED” Response.Redirect(”PrivateDocuments.aspx”) lblErrorMsg.Visible = True Else ’set the session variable NOT AGREED Session(”sessionLegal”) = “LEGAL DENIED” Label1.Text = “Access Denied unless agreement is checked.” lblErrorMsg.Visible = True End If End Sub
Now, on the “PrivateDocuments.aspx” page you have to add code so that the page will only display if the user has accepted the legal agreement otherwise they are routed back to the agreement page.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Session(”sessionLegal”) = “LEGALACCEPTED” Then pnlDocuments.Visible = True Else pnlDocuments.Visible = False Response.Redirect(”LegalAgreement.aspx”) End If If Page.IsPostBack Then ‘do nothing Else PopulateTree( ) End If End Sub
NOTES: You will need to have a textfile named “LegalAgreement.txt” with text in it. Be sure to edit the spacing in the textfile. Do NOT forget to close the StreamReader! Give it a try!