Upload
web1webteam
View
214
Download
0
Embed Size (px)
Citation preview
8/14/2019 Webcontrols.calendar Select Year
1/31
or the past 20 years, Johnsie Toys has been manufacturing and selling toys for
The companys top management officials are often on the road while trying to expand the
business to those parts of the world where the company does not yet have retail outlets. For
those officials to be able to efficiently manage the functioning of the company, they need to have
access to appropriate and updated information. To ensure that this is the case, four months ago
the company developed a Web site for internal use by the management. This Web site can be
accessed from any place in the world to obtain the required information.The Web site provides
several features that enable access to the following details:
Performance results of the company
Policies the company follows
Sales made by the retail outlets
Resource allocation and utilization
In addition, the Web site also provides a chat application that enables the officials to discuss
important matters online. All these features of the Web site help the officials to analyze the
current performance and plan for the future. Another significant use of this Web site is to provide
data for preparation of reports for presentations and seminars.
Since the introduction of this Web site four months ago, developers have constantly endeavored
to improve the site by providing more useful features.The latest suggestion,which topmanagement has just approved, is to have an application on the Web site that provides sales data
for different regions according to particular dates or years. This application, called SalesData,
will help in timely identification of sales trends so that management can make quick decisions and
formulate effective sales strategies. This application will also make it possible to assess daily or
yearly performance of the regions based on their sales, which will facilitate making decisions
about the commissions for the various regions. Moreover, by using this application, the officials
can monitor sales on a daily basis.
After analyzing the various available technologies, management decides to develop the
application using Visual Basic.NET and ADO.NET as the data access model because the .NET
Framework makes it easy to develop applications for the distributed Web environment and
supports cross-platform execution and interoperability. In addition, the .NET Framework makes
8/14/2019 Webcontrols.calendar Select Year
2/31
data available anytime, anywhere, and on any device.The choice of ADO.NET as the data access
model is quite obvious because it optimally utilizes the benefits of the .NET Framework. Currently,
it is the most efficient data access model for highly distributed Web applications.
Management chooses a five-member team, named the SalesDataTeam, to develop thisapplication. All the members of the SalesDataTeam are experienced programmers who have
developed applications using Visual Basic.NET and ADO.NET.
Before beginning to develop the application, the members of the SalesDataTeam determine the
development life cycle of the SalesData project. This life cycle is discussed in the following
section.
Project Life CycleEvery project has a development life cycle. Generally, the life cycle of a project consists of the
following three phases:
Project start
Project execution
Project end
Theproject startphase involves preparing the project plan and determining the desired result of
each phase. It also involves listing all the tasks that needs to be performed.This exhaustive list is
based on the research of the project team. After preparing this list, the team decides which tasks
are the most crucial. In addition, during this phase, the project manager assigns responsibilities to
the team members based on their expertise and experience.
The next phase of the project life cycle is the project execution phase. This phase involves the
actual development of the project. In this phase, the SalesDataTeam develops the SalesData
application. The project execution phase is divided into the following sequential stages:
Requirements analysis
High-level design
Low-level design
Construction
Testing
8/14/2019 Webcontrols.calendar Select Year
3/31
Acceptance
These stages will be discussed in detail in the next few sections.The last phase of the project life
cycle is the project end phase. During this phase, which takes place after the application is
deployed, the development team sorts out the problems.
Requirements Analysis
The requirements analysis stage involves analysis of the various requirements that the
application is expected to meet.This analysis identifies all the requirements to which the
application needs to cater.
In this stage, the SalesDataTeam asks the management officials what their requirements for the
SalesData application are. The team interviews the officials to find out all the elements they
consider before making a decision about the sales strategies. In addition, the SalesDataTeam
evaluates the applications that are currently on the company Web site to ascertain what features
those applications are not offering that might be beneficial. Then, the team analyzes its findings
and arrives at a consensus regarding the requirements for the SalesData application.
After gathering this information, the team decides that the SalesData application should enable auser to:
Select the desired region
Select a particular date or year
View the sales data after the user selects the region and date or year
High-Level DesignAfter the team identifies the requirements for the application, the next stage is to decide on the
formats for accepting the input and displaying the output of the application. During this high-level
design stage, the team documents all the specifications regarding the functioning of the
application, and then the project manager approves the design of the project.
During this stage, the SalesDataTeam designs a Web form that enables a user to select a
particular region from a list. Then, the user can choose a date (by selecting it from a calendar thatis displayed) or a year (by selecting it from a list).This form provides a button that, when clicked,
displays the sales data for the selected choices in a tabular format. If the required data does not
exist in the database, an appropriate message displays. Furthermore, the main form also provides
a button to reset all the controls.
8/14/2019 Webcontrols.calendar Select Year
4/31
Low-Level Design
The low-level design stage involves preparing a detailed design of the various modules to be used
for the application. In this stage, the SalesDataTeam makes decisions about how to establish a
connection with the relevant database and how to access the required data. The team alsodecides which classes and methods to use for developing the application. The data needed by the
SalesData application is available in a single table database.
Construction
The construction stage is the stage in which the development team builds the application. The
output of the low-level design stage is used as the input for this stage.In this stage, the
development team divides the responsibilities of the development work for the applicationdesigning the forms and writing the code among its members, and then the team carries out
the tasks.
Testing
The testing stage deals with the testing of the application after it is developed. In this stage, the
QA (quality assurance) team of the company (a team other than the development team) tests the
functionality of the application to ensure that it meets all the requirements specified in therequirements analysis stage. The QA team tests the application in various scenarios. It also tests
the application against the requirements specified in the requirements analysis stage and then
prepares a report of the test results. After the QA team gives this test report to the development
team, the development team rectifies the problems in the application.
Acceptance
In this stage, the company carries out testing of the projects developed for the clients.This testingis performed in accordance with the standards defined by the industry. The successful testing of
the project in this stage signifies the final acceptance of the project before release to the client. In
the case of the SalesData application, the QA team gives the final acceptance because this
application is being developed for the internal use of the company, not for any external client.
After the deployment of the application on the Web site, the SalesDataTeam provides support to
users if they face any problems while running the application.
Now, lets take a look at the structure of the database that the SalesData application will use.
The Database Structure
8/14/2019 Webcontrols.calendar Select Year
5/31
The database that the SalesData application will use to retrieve the desired sales data is a
Microsoft Access database called Sales. This database contains only one table: Sales. Figure 7-1
displays the design of the Sales table.
FIGURE 7-1 The design of the Sales table
The Sales table has Product Code as the primary key, and its data type is text. It also contains the
product name, units sold, price, date of sale, region, and total sales.
Summary
In this chapter, you learned that Johnsie Toys, a U.S. toy company interested in expanding
globally, uses an internal Web site for which a new application needs to be developed. Thecompany names the application SalesData and forms a five-member development team named
SalesDataTeam.
After this introduction, you learned about the different phases of the development life cycle of a
project and how the SalesDataTeam works through these phases. Finally, you learned about the
structure of the Sales database that the SalesData application will use. In the next chapter, you
will find out how to develop the SalesData application.
The Designing of Forms for the Application
As discussed in Chapter 7, the high-level design for the application involves designing two Web
forms. The main form of the SalesData application enables the user to specify the choices for
which the relevant sales data is displayed in the second form. Figure 8-1 displays the design of
the main form,and Figure 8-2 displays the design of the second form.
Before designing a Web form, you need to create it. The main form is created when you create a
new Web application project. (To learn more about creating a new Web application project and
creating and designing a Web form, refer to Appendix B, Introduction to Visual Basic.NET.) You
8/14/2019 Webcontrols.calendar Select Year
6/31
design a Web form by dragging the required controls from the Web Forms tab of the Toolbox and
then setting the properties for these controls. In the following sections, I talk about the various
controls on the two forms of the SalesData application and the properties assigned to them.
The Main FormName the main Web form ViewSalesData.aspx.As you can see in Figure 8-1, this form displays a
drop-down list containing all the regions. The form also allows users to specify whether they want
to view the sales data for a specific date or a specific year. This option is provided as a group of
radio buttons. The form also contains a calendar from which the user can select the desired date,
and another drop-down list enables the user to select the year. The form also contains two
buttons: View Sales and Reset. You use the View Sales button to display the relevant The three
labels on the form contain text for selecting the region, date, and year. You need to set threeproperties for each of these labels: ID, Text, and Visible. The ID property represents the object name
that you assign to the label to easily identify and refer to it in the code, and the Text property
represents the text that will appear for the label on the form.The value of the Visible property
indicates whether the label will be visible on the form. By default, the value of the Visible property
is set to True, which indicates that the label will be visible on the form. Table 8-1 describes the
properties for the three labels on the main form.
FIGURE 8-1 The design of the main form for the application
8/14/2019 Webcontrols.calendar Select Year
7/31
FIGURE 8-2 The design of the second form for the application
data in tabular format, and you use the Reset button to reset all the controls on the main form.
property list, select FlowLayout
Labels
The Visible property for the LblYear and LblDate labels is specified as False because these labels are not
visible on the main form when the application loads this form. These labels are visible only after
the user specifies whether he or she wants to view the sales data for a specific date or a specificyear. This involves setting validations,which Ill discuss in the How the Main Form Functions
section later in this chapter.
Drop-Down Lists
Below the LblRegion and LblYear labels on the form are drop-down lists for the regions and years,
respectively. The three properties set for these drop-down lists are ID, Items, and Visible. I mentioned
earlier in this chapter what the ID and Visible properties represent. The Items property represents thecollection of items that will appear in the drop-down list.
8/14/2019 Webcontrols.calendar Select Year
8/31
The ID property specified for the two drop-down lists is DDLRegion for the LblRegion label and DDLYear for
the LblYear label. The Visible property is set as True for the LblRegion label and as False for the LblYear
label. To specify the Items property, click on it in the Properties window, as shown in Figure 8-3.
FIGURE 8-3 The Itemsproperty selected in the Properties window
When you click on the Items property, an ellipsis button appears next to the (Collection) valuespecified for this property. Click on the ellipsis button to display the ListItem Collection Editor
dialog box, shown in Figure 8-4.
FIGURE 8-4 The ListItem Collection Editor dialog box
8/14/2019 Webcontrols.calendar Select Year
9/31
The ListItem Collection Editor dialog box contains two panes: Members and Properties. Because
no item has yet been specified for the drop-down list, both panes are empty. To add an item for
the list, click on the Add button. A ListItem appears in the Members pane and its properties
appear in the Properties pane, as shown in Figure 8-5.
In the ListItem Properties pane, you can specify whether you want the item to appear selected by
default in the drop-down list. The default functionality specifies that the first item you add for the
list appears selected in the drop-down list. If you want any other item to appear selected by
default, specify True for the Selected property of that item.In addition, you can specify the text that
you want for the added item and a value for the item. By default, the text that you specify
appears as the value of the item. Figure 8-6 displays the properties for the North item of the drop-
down list for the regions.
Now you can specify the properties for the other items in the drop-down list. Figure 8-7 displays
the items for the DDLRegion drop-down list.
FIGURE 8-5 The ListItem Collection Editor dialog box with an item added
8/14/2019 Webcontrols.calendar Select Year
10/31
FIGURE 8-6 The ListItem Collection Editor dialog box displaying the properties for the North item
8/14/2019 Webcontrols.calendar Select Year
11/31
FIGURE 8-7 The ListItem Collection Editor dialog box with items for the DDLRegion drop-down list
8/14/2019 Webcontrols.calendar Select Year
12/31
Figure 8-8 displays the items for the DDLYear drop-down list. For the item 2002, specify the Selected
property asTrue.
Below the LblDate label,add a calendar from which the user can select the desired date. Specify the
ID property for the calendar as CalSales and the Visible property as False.
Radio Buttons
A group of radio buttons on the form allows users to specify whether they want to view the sales
for a specific date or a specific year. Table 8-2 describes the properties you need to assign for
these radio buttons.
FIGURE 8-8 The ListItem Collection Editor dialog box with items for the DDLYear drop-down list
8/14/2019 Webcontrols.calendar Select Year
13/31
8/14/2019 Webcontrols.calendar Select Year
14/31
Note that the value for the GroupName property of both the radio buttons is set as GRP1. In this way,
you are specifying them as part of the same group, and the user is able to select only one radio
button from the group. The AutoPostBack property is set to True so that when the user selects a radio
button, the state of the radio buttons is automatically posted back to the server.
Buttons
The main form also contains two buttons.The properties that need to be assigned for these
buttons are described in Table 8-3.
When you add controls to the main form and specify their properties, the following code is
generated to indicate the declaration of all the objects that you drag to the Web form:
Protected WithEvents CalSales As System.Web.UI.WebControls.Calendar Protected WithEvents DDLYear As
System.Web.UI.WebControls.DropDownList Protected WithEvents DDLRegion As System.Web.UI.WebControls.DropDownList Protected
WithEvents BtnViewSales As System.Web.UI.WebControls.Button Protected WithEvents LblRegion As System.Web.UI.WebControls.Label
Protected WithEvents LblYear As System.Web.UI.WebControls.Label Protected WithEvents LblDate As System.Web.UI.WebControls.Label
Protected WithEvents RBDate As System.Web.UI.WebControls.RadioButton Protected WithEvents RBYear As
System.Web.UI.WebControls.RadioButton Protected WithEvents BtnReset As System.Web.UI.WebControls.Button
The Second FormNow that you know how to design the main form of the SalesData application, lets take a look at
the design of the second form. Name the second form SalesData.aspx. You can add the heading
Sales Data on the top of the form in the same way that you added the heading on the main form.
It also has the font size 7, is bold, and is center-aligned.
The label on the form has the ID property LBLUserMsg. This label is used to display information; the
text that is displayed depends on the choices the user makes in the main form. A data grid also
appears on the form; it displays the data retrieved from the database. To ensure that the font of
the column headings is bold, select Font under HeaderStyle, and then select True for the Bold property.
The form also contains a button with the ID property BtnOKand theText property OK.
The Functioning of the ApplicationNow that you understand the design of the two forms of the SalesData application, Ill discuss the
working of that application. First Ill explain how it works, and then Ill cover the code behind it.
8/14/2019 Webcontrols.calendar Select Year
15/31
How It Works
As you know, the SalesData application is a simple data access application that displays the sales
data of a region for a desired date or year. The main form (ViewSalesData.aspx) that appears
when the browser loads the application is displayed in Figure 8-9.
This form enables users to select the desired region from the drop-down list. To view the sales for
the selected region, users need to specify whether they want to view the sales for a specific date
or a specific year. To make this choice, they can simply select the relevant option. To view the
sales for a specific date, users needs to select the For a specific date option. In this case, the form
displays a calendar, as shown in Figure 8-10.This enables users to select the date for which they
want to view the sales data.
FIGURE 8-9 The main form in the browser
FIGURE 8-10 The main form with a calendar that enables users to select a date
8/14/2019 Webcontrols.calendar Select Year
16/31
After selecting the date from the calendar, users click on the View Sales button. This loads the
second form (SalesData.aspx), which displays the relevant data. Figure 8-11 displays the form
with the sales data of the North region on January 4, 2002.
FIGURE 8-11 The form displaying data for the selected region and date
8/14/2019 Webcontrols.calendar Select Year
17/31
If the database does not contain any records for the selection made by a user, an appropriate
message is displayed on the second form, as shown in Figure 8-12.
FIGURE 8-12 The form displaying a message when the relevant records are not present in the database
8/14/2019 Webcontrols.calendar Select Year
18/31
The second form displays an OK button, on which users can click to return to the main form. If
users want to view sales data for a specific year, they select the For a specific year option on the
main form. In this case, the form (as shown in Figure 8-13) displays a drop-down list from which
users can select the year for which they want to view the sales data.
After a user selects the year, the application works in the same way as it does when a user
selects a date. The main form of the application also provides a Reset button that,when clicked,
clears the selected choices to reset the controls to the original values.
The Code behind the Application
Now that you know how the SalesData application works, Ill discuss the code behind the
application that enables it to function.
How the Main Form Functions
As mentioned earlier in this chapter, when the main form of the application loads, some controls
(whose Visible property is set to False) are not visible to the user. These controls become visible or
remain hidden depending on the choices that the user makes.To enable this functionality,certain
validations are set.Take a look at the following code for the CheckedChanged event handler for the
selection in the radio button group. This code sets the Visible property of the various controls when
8/14/2019 Webcontrols.calendar Select Year
19/31
a user selects the For a specific date option. The code uses a simple If ... Then construct to execute
the logic.
8/14/2019 Webcontrols.calendar Select Year
20/31
Private Sub RBDate_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
RBDate.CheckedChanged
Set the Visible property for the controls BtnViewSales.Visible = True BtnReset.Visible = True LblYear.Visible = False LblDate.Visible =
True RBDate.Visible = False CalSales.Visible = True RBYear.Visible = False DDLYear.Visible = False
End Sub
Similarly, the following code specifies that the controls will be visible when a user selects the For
a specific year option:
Private Sub RBYear_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RBYear.CheckedChanged
Set the Visible property for the controls BtnViewSales.Visible = True BtnReset.Visible = True LblYear.Visible = True LblDate.Visible =False RBYear.Visible = False CalSales.Visible = False RBDate.Visible = False DDLYear.Visible = True
End Sub
After a user selects the appropriate choices in the main form and clicks on the View Sales button,
the following code associated with the Click event of the BtnViewSales button executes:
Private Sub BtnViewSales_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles BtnViewSales.Click Simple If loop to decide what SQL query to be executed according to the
selections made by the user
If CalSales.Visible = True And DDLYear.Visible = False Then
If DDLRegion.SelectedItem.Text = All Then SQL query to be stored in the SQLCommand property of the Standard module
Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price ($)], [Total Sales ($)] FROM Sales Where [Date
of Sale] = & CalSales.SelectedDate.Date.ToShortDateString &
Value to be stored in the ControlValue property of the
Standard module Standard.ControlValue = all the regions on & C a l S a l e s . S e l e c t e d D a t e . D a t e . T o S h o r t D a t e S t
r i n g
E l s e Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price ($)], [Total Sales ($)] FROM Sales Where
Region = & DDLRegion.SelectedItem.Text.Trim & and [Date of Sale] = & CalSales.SelectedDate & Standard.ControlValue =the & DDLRegion.SelectedItem.Text & region on & CalSales.SelectedDate.Date.ToShortDateString
End If ElseIf CalSales.Visible = False And DDLYear.Visible = True Then
8/14/2019 Webcontrols.calendar Select Year
21/31
If DDLRegion.SelectedItem.Text = All Then Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price
($)], [Total Sales ($)] FROM Sales Where Year([Date of Sale]) = & DDLYear.SelectedItem. Text & Standard.ControlValue = all the
regions in the year & D D L Y e a r . S e l e c t e d I t e m . T e x t
E l s e Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price ($)], [Total Sales ($)] FROM Sales Where
Region = & DDLRegion.SelectedItem.Text.Trim & and Year([Date of Sale]) = & DDLYear.SelectedItem. Text &
Standard.ControlValue = the &
DDLRegion.SelectedItem.Text & region in the year &
D D L Y e a r . S e l e c t e d I t e m . T e x t
End If
End If
Redirect to the SalesData page
R e s p o n s e . R e d i r e c t ( S a l e s D a t a . a s p x )
End Sub
In this code, the If ...Then construct contains code to determine the SQL query to be used according
to the selections made by the user. The SQL query that is generated retrieves records for the
Product Code, Product Name, Units Sold, Price ($), and Total Sales ($) columns of the Sales database. However,note that the Where condition of the query varies depending on the selections made by the user.
The Ifstatement in the code checks for the visibility of the calendar and the drop-down list for the
years. In case the Ifstatement evaluates to True, another If ... Then construct executes.
Note that this If ... Then construct uses the properties declared in the Standard module. The
Standard module is a Visual Basic.NET module with reusable code that is required across the
application. This module contains code for declaring two read-write properties. Before explainingthe SQL queries, Ill discuss the two properties declared in the Standard module. The following is
the code in the Standard module:
Module Standard
Declare two read-write property procedures
Declare a private variable to store the value assigned to the property
Private Command As String
Declare SQLCommand Property
Friend Property SQLCommand() As String
8/14/2019 Webcontrols.calendar Select Year
22/31
G e t
Return the value stored in the SQLCommand property
Return Command
End Get
Set(ByVal Value As String)
Set the property value and store it in the private variable,
Command
Command = Value End Set End Property
Private ControlSelectedValue As String Declare ControlValue Property Friend Property ControlValue() As String
G e t Return the value stored in the ControlValue property
Return ControlSelectedValue End Get Set(ByVal Value As String)
Set the property value and store it in the private variable, C o n t r o l S e l e c t e d V a l u e ControlSelectedValue = Value End Set
End Property End Module
The two properties declared in the Standard module are SQLCommand and ControlValue. In the previous
code, Command and ControlSelectedValue are private variables declared as strings and used for storing
the values assigned to the SQL-Command and ControlValue properties, respectively. Both the
SQLCommandand ControlValue properties are read-write properties for which the Set Property and Get
Property procedures are declared.The Set Property procedure sets the value of the property and stores
it in the private variable declared for it. The Get Property procedure returns the value stored in the
variable of the property.
Now, Ill discuss the following If ... Then construct (after the first Ifstatement evaluates to True) and
the SQL queries that are generated:
If CalSales.Visible = True And DDLYear.Visible = False Then
If DDLRegion.SelectedItem.Text = All Then Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price
($)], [Total Sales ($)] FROM Sales Where [Date of Sale] = & CalSales.SelectedDate.Date.ToShortDateString & Standard.ControlValue = all the regions on & C a l S a l e s . S e l e c t e d D a t e . D a t e . T o S h o r t D a t e S t r i n g
8/14/2019 Webcontrols.calendar Select Year
23/31
E l s e Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price ($)], [Total Sales ($)] FROM Sales Where
Region = & DDLRegion.SelectedItem.Text.Trim & and [Date of Sale] = & CalSales.SelectedDate & Standard.ControlValue =
the & DDLRegion.SelectedItem. Text & region on & C a l S a l e s . S e l e c t e d D a t e . D a t e . T o S h o r t D a t e S t r i n g
End If
The Ifstatement checks whether All is selected in the drop-down list for the regions. In case the If
statement evaluates toTrue, the Where condition of the SQL query specifies that the value in the
Date of Salecolumn should match the date selected in the calendar. The SQL query is stored in the
SQLCommand property declared in the Standard module. In addition, the selected option values also
get stored in the ControlValue property of the Standard module. (These values are used for
LBLUserMsg, a label youll learn about later in this chapter.) However, in case the Ifstatement
evaluates to False, the SQL query retrieves records based on a different Where condition.
Furthermore, if a user wants to view the sales data for a specific year, the first Ifstatement (which
checks for the visibility of the calendar and the drop-down list for the years) evaluates to False. In
that case, the ElseIf ... Then construct following the first If ... Then construct executes to determine the
SQL query to be used:
ElseIf CalSales.Visible = False And DDLYear.Visible = True Then
If DDLRegion.SelectedItem.Text = All Then Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price
($)], [Total Sales ($)] FROM Sales Where Year([Date of Sale]) = &
DDLYear.SelectedItem.Text & Standard.ControlValue = all the regions in the year & D D L Y e a r . S e l e c t e d I t e m . T e x t
E l s e Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price ($)], [Total Sales ($)] FROM Sales Where
Region = & DDLRegion.SelectedItem.Text.Trim & and Year([Date of Sale]) = & DDLYear.SelectedItem.Text &
Standard.ControlValue = the & DDLRegion.SelectedItem.Text & region in the year & DDLYear.SelectedItem.Text End If
When users click on the View Sales button, they are redirected to the SalesData.aspx page that
displays the data for the selected choices. The code for this redirection is also written in the Click
event of the View Sales button.
As mentioned earlier, you can use the Reset button to clear all the options the user selects. This is
possible because the Click event of the Reset button reloads the ViewSalesData.aspx page. The
code for this is as follows:
Private Sub BtnReset_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles BtnReset.Click Reload the page R e s p o n s e . R e d i r e c t ( V i e w S a l e s D a t a . a s p x
)
8/14/2019 Webcontrols.calendar Select Year
24/31
End Sub
How the Second Form Functions
Now that you know how the main form of the application functions, Ill discuss the functioning of
the second form. When a user clicks on the View Sales button on the main form, the followingcode attached to the Load event of the second form executes:
Create an object of the type OleDbConnection Dim Conn As OleDbConnection Private Sub Page_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Try block is used for code whose exceptions are handled by the catch block T r y Declare an integer variable to validate the number
of rows returned
Dim RowCount As Integer Specify the connection string Conn = New OleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0; & _ Data
source= & Request.PhysicalApplicationPath & /Sales.mdb;) Open the connection C o n n . O p e n ( ) Create an object of the
OleDbDataAdapter class and pass the SQL command and the connection information as parameters
Dim AdapObj As OleDbDataAdapter = New OleDbDataAdapter (Standard.SQLCommand, Conn) Create a dataset object Dim DstObj As
DataSet = New DataSet() Call the Fill method of the OleDbDataAdapter object to fil l the dataset AdapObj.Fill(DstObj, SalesTable)
Store the result as the number of rows returned RowCount = DstObj.Tables(SalesTable).Rows.Count Check the number of rows
stored in the RowCount variable If RowCount > 0 Then
If rows are greater than 0, then the data is displayed in the datagrid control Label to display information LBLUserMsg.Text = For &
Standard.ControlValue Specify the DataSource property of the control to the dataset object DataGrid1.DataSource = DstObj Bind the
data in the dataset to the control D a t a G r i d 1 . D a t a B i n d ( )
E l s e If no rows are returned, then the label is displayed with appropriate message LBLUserMsg.Text = No Records Available
End If Catch block is basically used to trap all the exceptions/error information that might occur in executing the code in the try
block.
Catch RunException As Exception Declare a variable of the type exception Write the error message for the user reference
Response.Write(Error Occured: & vbLf & RunException.ToString) The cleanup code comes here F i n a l l y Close the connection C o
n n . C l o s e ( ) End Try End Sub
In this code, the Try, Catch, and Finally blocks are used to write the code. The Try block is used for the
executable code. The Catch block is used for the code that handles the exception generated by the
code in the Try block. The Finally block is used to release the resources used.
As mentioned earlier in this chapter, for the second form (SalesData.aspx) to display the relevant
data retrieved from the database, the SalesData application makes use of ADO.NET. The database
that contains the relevant sales data, which the application needs to access, is a Microsoft Access
database. Therefore, the OLE DB .NET data provider is used to connect to the database, execute
8/14/2019 Webcontrols.calendar Select Year
25/31
commands, and retrieve results. Because the OLE DB .NET data provider is used, the
System.Data.OleDb namespace is imported so that you need not use the fully qualified names of the
classes and the objects:
Imports System.Data.OleDb
To establish a connection with the database, the OleDbConnection object is used and the connection
string property is declared.The following is the code to establish the connection:
Create an object of the type OleDbConnection Dim Conn As OleDbConnection Specify the connection string Conn = New
OleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0; & _ Data source= & Request.PhysicalApplicationPath & /Sales.mdb;) Open
the connection C o n n . O p e n ( )
This code creates an object, Conn, of the OleDbConnection class. This object is used to specify theconnection string, which provides the name of the provider as Microsoft.Jet.OLEDB.4.0and the data
source as the Sales database that can be accessed from the physical application path. Next, the
object Conn calls the Open() method. This method establishes an open connection with the
database.As I discussed in Chapter 3, Connecting to a SQL Server and Other Data Sources,
there are various ways of writing a connection string, such as writing the connection string as a
string or using the connection object to declare a connection string. The previous code uses the
connection object to declare the connection string.
After a connection is established with the database, OleDbDataAdapter is used to communicate
between the database and the dataset. For this, an object of the OleDbDataAdapter class is created,
and the SQL command and the connection information are passed to it as parameters. The code
for this is as follows:
Create an object of the OleDbDataAdapter class and
pass the SQL command and the connection information as parameters Dim AdapObj As OleDbDataAdapter = New OleDbDataAdapter(Standard.SQLCommand, Conn)
In this code, AdapObj is the object of the OleDbDataAdapter class.The SQLCommand property stored in the
Standard module and the connection information specified for the Conn object are the parameters
for the AdapObj object. Instead of using the AdapObj object, you can use an OleDbCommand object.
OleDbCommand is used for processing requests and returning results of these requests. If you want
to use the OleDbCommand object, use the following code:
Create the object of type OleDbDataAdapter Dim AdapObj As OleDbDataAdapter = New OleDbDataAdapter() Create the object of
type OleDbCommand Dim DbCmd As New OleDbCommand() Set the CommandText property of the OleDbCommand object to the SQL
statement that uses the property procedure declared in the Standard module DbCmd.CommandText = Standard.SQLCommand Set
the Connection property of the OleDbCommand object to the OleDbConnection object, which the OleDbCommand object will use as
8/14/2019 Webcontrols.calendar Select Year
26/31
the data source connection for fetching the data DbCmd.Connection = Conn Set the SelectCommand property of the
OleDbDataAdapter object to the OleDbCommand object AdapObj.SelectCommand = DbCmd
In this code, AdapObj is the object of the OleDbDataAdapter class,and DbCmd is the object of the
OleDbCommand class. The CommandText property of the DbCmd object is set to the SQLCommand property
stored in the Standard module, and the Connection property of the DbCmd object is set to the Conn
object, which stores the connection information. Then, the SelectCommand property of the AdapObj
object is set to the DbCmd object.
As you know, you use the Fill()method of the OleDBDataAdapter class to fill the dataset with the
relevant data that is fetched from the database.This data is then displayed in the data grid on the
form. The code for the Fill() method is as follows:
Create an object of the type DataSet Dim DstObj As DataSet = New DataSet() Call the Fill method of the OleDbDataAdapter object to
fill the dataset AdapObj.Fill(DstObj, SalesTable) Store the result as the number of rows returned RowCount =
DstObj.Tables(SalesTable).Rows.Count Check the number of rows stored in the RowCount variable If RowCount > 0 Then If rows are
greater than 0, then the data is displayed in the datagrid control Label to display information LBLUserMsg.Text = For &
Standard.ControlValue Specify the DataSource property of the control to the dataset object DataGrid1.DataSource = DstObj Bind the
data in the dataset to the control D a t a G r i d 1 . D a t a B i n d ( )
E l s e If no rows are returned, then the label is displayed with appropriate message LBLUserMsg.Text = No Records Available
End If
In this code, an object (DstObj) of the dataset is created. Then, the Fill() method of the
OleDbDataAdapter class is called to fill the dataset with the relevant data.The dataset object and the
name of the table that will store the data are provided as parameters of the Fill() method. Here, for
the table name parameter, it is not necessary for the table name to be the same as it is in the
database. You can give any relevant name to the table. When the Fill() method is called, the
RowCount variable, which is declared as an integer, is used to store the count of rows that arereturned in the dataset as the result of the query executed.
An If ... Then construct is used for the code to bind the result to the data grid control. The If
statement of the construct checks whether the number of rows returned as the result is more
than zero. If the database contains records for the choices that the user selects on the main form,
then the Ifstatement will evaluate toTrue. In this case, the LBLUserMsg label displays the text For
and the value that is stored in the ControlValue property of the Standard module. The DstObj object is
specified in the DataSource property of the DataGrid control. The data in the dataset is binded to theDataGrid control by using the DataBind property. This indicates that the data from the dataset will be
displayed in the data grid. However, if the database does not contain any record for the selected
choices,then no rows will be fetched in the dataset. In that case, the Ifstatement evaluates to F a l
8/14/2019 Webcontrols.calendar Select Year
27/31
s e, and the E l s e statement of the con s t ruct exe c u t e s . Th e re f o re, t h e LBLUserMsg label will
display the text No Records Available. Once the required data is retrieved from the database,
the Conn object is used to call the Close() method, which closes the open connection to the
database.
After viewing the sales data, the user can click on the OKbutton on the form.This redirects the
user to the ViewSalesData.aspx page. The following is the code attached to the Click event of the
OKbutton:
Private Sub BtnOK_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles BtnOK.Click
Redirect to the ViewSalesData page
R e s p o n s e . R e d i r e c t ( V i e w S a l e s D a t a . a s p x )
End Sub
The Complete Example Code
Now that you have learned about the code that enables the functioning of the SalesData
application, in this section I provide the complete code of the ViewSalesData.aspx and the
SalesData.aspx pages of the application. Listing 8-1 is the code of the ViewSalesData.aspx page,
and Listing 8-2 is the code of the SalesData.aspx page. These example files (Vi ew Sa l e s D a t a
. a s p x . vb and SalesData.aspx.vb) are included on the Web site www.premierpressbooks.com/
downloads.asp.
Listing 8-1 ViewSalesData.aspx.vb
Public Class WebForm1
Inherits System.Web.UI.Page
Protected WithEvents CalSales As System.Web.UI.WebControls.Calendar
Protected WithEvents DDLYear As System.Web.UI.WebControls.DropDownList Protected WithEvents DDLRegion As
System.Web.UI.WebControls.DropDownList Protected WithEvents BtnViewSales As System.Web.UI.WebControls.Button Protected
WithEvents LblRegion As System.Web.UI.WebControls.Label Protected WithEvents LblYear As System.Web.UI.WebControls.Label
Protected WithEvents LblDate As System.Web.UI.WebControls.Label Protected WithEvents RBDate As
System.Web.UI.WebControls.RadioButton Protected WithEvents RBYear As System.Web.UI.WebControls.RadioButton Protected
WithEvents BtnReset As System.Web.UI.WebControls.Button
#Region Web Form Designer Generated Code
This call is required by the Web Form Designer. Private Sub InitializeComponent()
End Sub
8/14/2019 Webcontrols.calendar Select Year
28/31
Private Sub Page_Init(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Init CODEGEN: This method call is required by the Web Form Designer Do not modify
it using the code editor. I n i t i a l i z e C o m p o n e n t ( )
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Put user code to initialize
the page here End Sub
Private Sub BtnViewSales_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles BtnViewSales.Click Simple If loop to decide what SQL query to be executed according to the
selections made by the user
If CalSales.Visible = True And DDLYear.Visible = False Then
If DDLRegion.SelectedItem.Text = All Then SQL query to be stored in the SQLCommand property procedure of the Standard module
Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price ($)], [Total Sales ($)] FROM Sales Where [Date
of Sale] = & CalSales.SelectedDate.Date.ToShortDateString &
Value to be stored in the ControlValue property procedure
of the Standard module Standard.ControlValue = all the regions on & C a l S a l e s . S e l e c t e d D a t e . D a t e . T o S h o r t D a
t e S t r i n g
E l s e Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price ($)], [Total Sales ($)] FROM Sales Where
Region = & DDLRegion.SelectedItem.Text.Trim & and [Date of Sale] = & CalSales.SelectedDate & Standard.ControlValue =
the & DDLRegion.SelectedItem.Text & region on & CalSales.SelectedDate.Date.ToShortDateString
End If ElseIf CalSales.Visible = False And DDLYear.Visible = True Then
If DDLRegion.SelectedItem.Text = All Then Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price
($)], [Total Sales ($)] FROM Sales Where Year([Date of Sale]) = & DDLYear.SelectedItem.Text & Standard.ControlValue = all the
regions in the year & D D L Y e a r . S e l e c t e d I t e m . T e x t
E l s e Standard.SQLCommand = SELECT [Product Code], [Product Name], [Units Sold], [Price ($)], [Total Sales ($)] FROM Sales WhereRegion = & DDLRegion.SelectedItem.Text.Trim & and Year([Date of Sale]) = & DDLYear.SelectedItem.Text &
Standard.ControlValue = the & DDLRegion.SelectedItem.Text & region in the year & DDLYear.SelectedItem.Text
End If End If
di h S l
8/14/2019 Webcontrols.calendar Select Year
29/31
Redirect to the SalesData page
R e s p o n s e . R e d i r e c t ( S a l e s D a t a . a s p x ) End Sub
Private Sub RBDate_CheckedChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles RBDate.CheckedChanged Set the Visible property for the controls BtnViewSales.Visible = True
BtnReset.Visible = True LblYear.Visible = False LblDate.Visible = True RBDate.Visible = False CalSales.Visible = True RBYear.Visible =
False DDLYear.Visible = False
End Sub
Private Sub RBYear_CheckedChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles RBYear.CheckedChanged Set the Visible property for the controls BtnViewSales.Visible = True
BtnReset.Visible = True LblYear.Visible = True LblDate.Visible = False RBYear.Visible = False CalSales.Visible = False RBDate.Visible =
False DDLYear.Visible = True
End If End Sub
Private Sub BtnReset_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles BtnReset.Click Reload the page R e s p o n s e . R e d i r e c t ( V i e w S a l e s D a t a . a s p x
)
End Sub End Class
Listing 8-2 SalesData.aspx.vb
Imports System.Data.OleDb
Public Class SalesData Inherits System.Web.UI.Page Protected WithEvents LBLUserMsg As System.Web.UI.WebControls.Label Protected
WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid Protected WithEvents BtnOK As System.Web.UI.WebControls.Button
Create an object of the type OleDbConnection Dim Conn As OleDbConnection
#Region Web Form Designer Generated Code This call is required by the Web Form Designer.
Private Sub InitializeComponent() End Sub
Private Sub Page_Init(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Init CODEGEN: This method call is required by the Web Form Designer Do not modifyit using the code editor. I n i t i a l i z e C o m p o n e n t ( )
End Sub #End Region
8/14/2019 Webcontrols.calendar Select Year
30/31
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Try block is used for code
whose exceptions are handled by the catch block T r y
Declare an integer variable to validate the number of rows returned Dim RowCount As Integer Specify the connection string Conn =
New OleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0; & _ Data source= & Request.PhysicalApplicationPath & /Sales.mdb;)
Open the connection C o n n . O p e n ( ) Create an object of the OleDbDataAdapter class and
pass the SQL command and the connection information as parameters Dim AdapObj As OleDbDataAdapter = New OleDbDataAdapter
(Standard.SQLCommand, Conn) Create an object of the type DataSet Dim DstObj As DataSet = New DataSet() Call the Fill method of
the OleDbDataAdapter object to fill the dataset AdapObj.Fill(DstObj, SalesTable) Store the result as the number of rows returned
RowCount = DstObj.Tables(SalesTable).Rows.Count Check the number of rows stored in the RowCount variable If RowCount > 0 Then
If rows are greater than 0, then the data is displayed in the datagrid control Label to display information LBLUserMsg.Text = For &
Standard.ControlValue Specify the DataSource property of the control to the dataset object DataGrid1.DataSource = DstObj Bind the
data in the dataset to the control D a t a G r i d 1 . D a t a B i n d ( )
E l s e If no rows are returned, then the label is displayed with appropriate message LBLUserMsg.Text = No Records Available
End If Catch block is basically used to trap all the exceptions/error information that might occur in executing the code in the try
block.
Catch RunException As Exception Declare a variable of the type exception Write the error message for the user reference
Response.Write(Error Occured: & vbLf & RunException.ToString) The cleanup code comes here
F i n a l l y Close the connection C o n n . C l o s e ( )
End Try End Sub
Private Sub BtnOK_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles BtnOK.Click Redirect to the ViewSalesData page R e s p o n s e . R e d i r e c t ( V i e w S a l e
s D a t a . a s p x )
End Sub End Class
Summary
In this chapter, I showed you how to design the two forms used by the SalesData application. You
also learned about the working of the application. Next, you saw the code attached to the various
controls of the forms. Finally, you learned how the connection to the database is established and
how the data retrieved from the database is displayed to the users. In the next chapter, I explain
h t D t Ad t C fi ti Wi d t fi d t d t d il t bli h
8/14/2019 Webcontrols.calendar Select Year
31/31
how to use Data Adapter Configuration Wizard to configure a data adapter and easily establish
the connection with the database.