Introducing Web Forms: VB Intro1.aspx
Introducing Web Forms: VB Intro1.aspx
• The ability to create and use reusable UI controls that can encapsulate common functionality and thus reduce the amount
of code that a page developer has to write.
• The ability for developers to cleanly structure their page logic in an orderly fashion (not "spaghetti code").
• The ability for development tools to provide strong WYSIWYG design support for pages (existing ASP code is opaque to
tools).
This section of the QuickStart provides a high-level code walkthrough of some key ASP.NET Web Forms features. Subsequent
sections of the QuickStart drill down into more specific details.
VB Intro1.aspx
VB Intro2.aspx
[Run Sample] | [View Source]
Important: Unlike with ASP, the code used within the above <% %> blocks is actually compiled--not interpreted using a script
engine. This results in improved runtime execution performance.
ASP.NET page developers can utilize <% %> code blocks to dynamically modify HTML output much as they can today with ASP.
For example, the following sample demonstrates how <% %> code blocks can be used to interpret results posted back from a
client.
VB Intro3.aspx
VB Intro4.aspx
VB Intro5.aspx
VB Intro7.aspx
VB Intro8.aspx
VB Intro9.aspx
VB Intro10.aspx
VB Intro11.aspx
VB Intro12.aspx
VB Intro13.aspx
[Run Sample] | [View Source]
Section Summary
1. ASP.NET Web Forms provide an easy and powerful way to build dynamic Web UI.
2. ASP.NET Web Forms pages can target any browser client (there are no script library or cookie requirements).
3. ASP.NET Web Forms pages provide syntax compatibility with existing ASP pages.
4. ASP.NET server controls provide an easy way to encapsulate common functionality.
5. ASP.NET ships with 45 built-in server controls. Developers can also use controls built by third parties.
6. ASP.NET server controls can automatically project both uplevel and downlevel HTML.
7. ASP.NET templates provide an easy way to customize the look and feel of list server controls.
8. ASP.NET validation controls provide an easy way to do declarative client or server data validation.
Working with Server Controls
This section of the QuickStart illustrates some common core concepts and common actions performed by end users when using
ASP.NET server controls within a page.
VB Controls1.aspx
VB Controls2.aspx
VB Controls3.aspx
VB Controls5.aspx
VB Controls6.aspx
The Web is a flexible environment for user interfaces, with extreme variations in the look and feel of different Web sites. The
widespread adoption of cascading style sheets (CSS) is largely responsible for the rich designs encountered on the Web. All of
ASP.NET's HTML server controls and Web server controls have been designed to provide first-class support for CSS styles. This
section discusses how to use styles in conjunction with server controls and demonstrates the very fine control over the look and
feel of your Web Forms that they provide.
VB Style1.aspx
VB Style2.aspx
</script>
VB Style3.aspx
VB Style4.aspx
VB Style5.aspx
VB Style6.aspx
[Run Sample] | [View Source]
As with HTML server controls, you can apply styles to Web server controls using a CSS class definition. The WebControl base
class exposes a String property named CssClass for setting the style class:
VB Style7.aspx
VB Style8.aspx
MyLogin.ApplyStyle (MyStyle)
MyPassword.ApplyStyle (MyStyle)
MySubmit.ApplyStyle (MyStyle)
End Sub
</script>
C# VB JScript
The following sample demonstrates the code above.
VB Style9.aspx
Section Summary
1. ASP.NET's HTML server control and Web server control families provide first-class support for CSS styles.
2. Styles may be applied by setting either the style or the class attributes of a control. These settings are accessible
programmatically through the control's Attributes collection. In the case of HTML server controls, individual values for
style-attribute keys can be retrieved from the control's Style collection.
3. Most commonly used style settings are exposed on Web server controls as strongly typed properties of the control
itself.
4. The System.Web.UI.WebControls namespace includes a Style base class that encapsulates common style
attributes. Many Web server controls expose properties of this type to control individual rendering elements.
5. Styles may be set programmatically on Web server controls using the ApplyStyle method of the WebControl base
class.
Server Control Form Validation
Introduction to Validation
Types of Validation Controls
Client-Side Validation
Displaying Validation Errors
Working with CompareValidator
Working with RangeValidator
Working with Regular Expressions
Performing Custom Validation
Bringing It All Together
Section Summary
Introduction to Validation
The Web Forms framework includes a set of validation server controls that provide an easy-to-use but powerful way to check
input forms for errors and, if necessary, display messages to the user.
Validation controls are added to a Web Forms page like other server controls. There are controls for specific types of validation,
such as range checking or pattern matching, plus a RequiredFieldValidator that ensures that a user does not skip an entry
field. You can attach more than one validation control to an input control. For example, you might specify both that an entry is
required and that it must contain a specific range of values.
Validation controls work with a limited subset of HTML and Web server controls. For each control, a specific property contains the
value to be validated. The following table lists the input controls that may be validated.
Control Validation Property
HtmlInputText Value
HtmlTextArea Value
HtmlSelect Value
HtmlInputFile Value
TextBox Text
ListBox SelectedItem.Value
DropDownList SelectedItem.Value
RadioButtonList SelectedItem.Value
VB Validator1.aspx
Client-Side Validation
The validation controls always perform validation checking in server code. However, if the user is working with a browser that
supports DHTML, the validation controls can also perform validation using client script. With client-side validation, any errors are
detected on the client when the form is submitted to the server. If any of the validators are found to be in error, the submission
of the form to the server is cancelled and the validator's Text property is displayed. This permits the user to correct the input
before submitting the form to the server. Field values are revalidated as soon as the field containing the error loses focus, thus
providing the user with a rich, interactive validation experience.
Note that the Web Forms page framework always performs validation on the server, even if the validation has already been
performed on the client. This helps prevent users from being able to bypass validation by impersonating another user or a
preapproved transaction.
Client-side validation is enabled by default. If the client is capable, uplevel validation will be performed automatically. To disable
client-side validation, set the page's ClientTarget property to "Downlevel" ("Uplevel" forces client-side validation).
VB Validator2.aspx
VB Validator3.aspx
VB Validator5.aspx
VB Validator6.aspx
VB Validator7.aspx
VB Validator8.aspx
VB Validator9.aspx
Section Summary
1. Validator controls can be used to validate input on any Web Forms page.
2. More than one control can be used on a given input field.
3. Client-side validation may be used in addition to server validation to improve form usability.
4. The CustomValidator control lets the user define custom validation criteria.
Web Forms User Controls
VB Pagelet1.aspx
VB Pagelet2.aspx
VB Pagelet4.aspx
VB Pagelet5.aspx
VB Pagelet6.aspx
C# VB JScript
The type of the user control is determined by a ClassName attribute on the Control directive. For example, a user control
saved with the file name "pagelet7.ascx" is assigned the strong type "Pagelet7CS" as follows:
<%@ Control ClassName="Pagelet7CS" %>
Because the LoadControl method returns a type of System.Web.UI.Control, it must be cast to the appropriate strong type in
order to set individual properties of the control. Finally, the user control is added to the base page's ControlCollection.
VB Pagelet7.aspx
Section Summary
1. User controls allow developers to easily define custom controls using the same programming techniques as for writing
Web Forms pages.
2. As a matter of convention, an .ascx file name extension is used to indicate such controls. This ensures that a user
control file cannot be executed as a standalone Web Forms page.
3. User controls are included into another Web Forms page using a Register directive, which specifies a TagPrefix,
TagName, and Src location.
4. After the user control has been registered, a user control tag may be placed in a Web Forms page as an ordinary
server control (including the runat="server" attribute).
5. The public fields, properties, and methods of a user control are promoted to public properties (tag attributes) and
methods of the control in the containing Web Forms page.
6. User controls participate in the complete execution lifecycle of every request and can handle their own events,
encapsulating some of the page logic from the containing Web Forms page.
7. User controls should not contain any form controls but should instead rely on their containing Web Forms page to
include one if necessary.
8. User controls may be created programmatically using the LoadControl method of the System.Web.UI.Page class.
The type of the user control is determined by the ASP.NET runtime, following the convention filename_extension.
9. The strong type for a user control is available to the containing Web Forms page only if a Register directive is
included for the user control (even if there are no user control tags actually declared).
Data Binding Server Controls
Although this syntax looks similar to the ASP shortcut for Response.Write -- <%= %> -- its behavior is quite different. Whereas
the ASP Response.Write shortcut syntax was evaluated when the page was processed, the ASP.NET data binding syntax is
evaluated only when the DataBind method is invoked.
DataBind is a method of the Page and all server controls. When you call DataBind on a parent control, it cascades to all of the
children of the control. So, for example, DataList1.DataBind() invokes the DataBind method on each of the controls in the
DataList templates. Calling DataBind on the Page -- Page.DataBind() or simply DataBind() -- causes all data binding
expressions on the page to be evaluated. DataBind is commonly called from the Page_Load event, as shown in the following
example.
C# VB JScript
You can use a binding expression almost anywhere in the declarative section of an .aspx page, provided it evaluates to the
expected data type at run time. The simple property, expression, and method examples above display text to the user when
evaluated. In these cases, the data binding expression must evaluate to a value of type String. In the collection example, the
data binding expression evaluates to a value of valid type for the DataSource property of ListBox. You might find it necessary
to coerce the type of value in your binding expression to produce the desired result. For example, if count is an integer:
Number of Records: <%# count.ToString() %>
VB DataBind1.aspx
VB DataBind3.aspx
VB DataBind4.aspx
VB DataBind5.aspx
VB DataBind6.aspx
C# VB JScript
This syntax can be complex and difficult to remember. In contrast, DataBinder.Eval is simply a method with three arguments:
the naming container for the data item, the data field name, and a format string. In a templated list like DataList, DataGrid, or
Repeater, the naming container is always Container.DataItem. Page is another naming container that can be used with
DataBinder.Eval.
C# VB JScript
The format string argument is optional. If it is omitted, DataBinder.Eval returns a value of type object, as shown in the
following example.
C# VB JScript
It is important to note that DataBinder.Eval can carry a noticeable performance penalty over the standard data binding syntax
because it uses late-bound reflection. Use DataBinder.Eval judiciously, especially when string formatting is not required.
VB DataBind7.aspx
Section Summary
1. The ASP.NET declarative data binding syntax uses the <%# %> notation.
2. You can bind to data sources, properties of the page or another control, collections, expressions, and results returned
from method calls.
3. List controls can bind to collections that support the ICollection, IEnumerable, or IListSource interface, such as
ArrayList, Hashtable, DataView, and DataReader.
4. DataBinder.Eval is a static method for late binding. Its syntax can be simpler than the standard data binding syntax,
but performance is slower.
Server-Side Data Access
• A connection represents a physical connection to some data store, such as SQL Server or an XML file.
• A command represents a directive to retrieve from (select) or manipulate (insert, update, delete) the data store.
• A dataset represents the actual data an application works with. Note that datasets are always disconnected from their
source connection and data model and can be modified independently. However, changes to a dataset can be easily
reconciled with the originating data model.
For a more detailed walkthrough of the managed data access solution in the common language runtime, please read the
ADO.NET Overview section of this tutorial.
C# VB JScript
As mentioned earlier in this section, the benefit of using a dataset is that it gives you a disconnected view of the database. You
can operate on a dataset in your application, and then reconcile your changes with the actual database later. For long-running
applications this is often the best approach. For Web applications, you are usually performing short operations with each request
(commonly to simply display the data). You often don't need to hold a DataSet object over a series of several requests. For
situations like these, you can use a SqlDataReader.
A SqlDataReader provides a forward-only, read-only pointer over data retrieved from a SQL database. To use a
SqlDataReader, you declare a SqlCommand instead of a SqlDataAdapter. The SqlCommand exposes an ExecuteReader
method that returns a SqlDataReader. Note also that you must explicitly open and close the SqlConnection when you use a
SqlCommand. After a call to ExecuteReader, the SqlDataReader can be bound to an ASP.NET server control, as you'll see in
the next section.
myConnection.Open()
...
myConnection.Close()
C# VB JScript
When performing commands that do not require data to be returned, such as inserts, updates, and deletes, you also use a
SqlCommand. The command is issued by calling an ExecuteNonQuery method, which returns the number of rows affected.
Note that the connection must be explicitly opened when you use the SqlCommand; the SqlDataAdapter automatically
handles opening the connection for you.
myCommand.Connection.Open()
myCommand.ExecuteNonQuery()
myCommand.Connection.Close()
C# VB JScript
Important: Always remember to close the connection to the data model before the page finishes executing. If you do not close
the connection, you might inadvertently exhaust the connection limit while waiting for the page instances to be handled by
garbage collection.
VB DataGrid1.aspx
MyDataGrid.DataSource=ds.Tables("Authors").DefaultView
MyDataGrid.DataBind()
C# VB JScript
An alternative syntax is to specify both a DataSource and a DataMember. In this case, ASP.NET automatically gets the
DefaultView for you.
MyDataGrid.DataSource=ds
MyDataGrid.DataMember="Authors"
MyDataGrid.DataBind()
C# VB JScript
You can also bind directly to a SqlDataReader. In this case you are only displaying data, so the forward-only nature of the
SqlDataReader is perfectly suited to this scenario, and you benefit from the performance boost that SqlDataReader provides.
VB DataGrid1.1.aspx
C# VB JScript
Important: Note that the DataGrid's EnableViewState property has been set to false. If the data will be populated in each
request, there is no benefit to having the DataGrid store state information to be sent through a round trip with form posts.
Because the DataGrid stores all of its data when maintaining state, it is important to turn it off when appropriate to improve the
performance of your pages.
DataGrid2.aspx statically populates the values of the select box, but this will not work well if those values ever change in the
database. Because the select HtmlControl also supports an IEnumerable DataSource property, you can use a select query to
dynamically populate the select box instead, which guarantees that the database and user interface are always in sync. The
following sample demonstrates this process.
VB DataGrid3.aspx
VB DataGrid4.aspx
<Columns>
<asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update" />
</Columns>
</ASP:DataGrid>
On the DataGrid tag itself, you wire event handlers to each of the commands fired from the EditCommandColumn. The
DataGridCommandEventArgs argument of these handlers gives you direct access to the index selected by the client, which
you use to set the DataGrid's EditItemIndex. Note that you need to re-bind the DataGrid for the change to take effect, as
shown in the following example.
C# VB JScript
When a row of the DataGrid is being edited, the EditCommandColumn renders the Update and Cancel links. If the client
selects Cancel, you simply set the EditItemIndex back to -1. If the client selects Update, however, you need to execute your
update command to the database. Performing an update query requires that you know the primary key in the database for the
row you wish to update. To support this, the DataGrid exposes a DataKeyField property that you can set to the field name for
the primary key. In the event handler wired to the UpdateCommand, you can retrieve the key name from the DataGrid's
DataKeys collection. You index into this collection using the ItemIndex of the event, as shown in the following example.
myCommand.Parameters("@Id").Value = MyDataGrid.DataKeys(CType(E.Item.ItemIndex, Integer))
C# VB JScript
At the end of the Update event handler, you set the EditItemIndex back to -1. The following sample demonstrates this code in
action.
VB DataGrid6.aspx
VB DataGrid7.aspx
VB DataGrid8.aspx
VB DataGrid9.aspx
VB DataGrid10.aspx
<script>
Protected Sub MyDataGrid_Sort(Src As Object, E As DataGridSortCommandEventArgs)
...
DataView Source = ds.Tables("Authors").DefaultView
Source.Sort = E.SortExpression
MyDataGrid.DataBind()
End Sub
</script>
<form runat="server">
<ASP:DataGrid id="MyDataGrid" OnSortCommand="MyDataGrid_Sort" AllowSorting="true"
runat="server" />
</form>
C# VB JScript
The following sample shows this code in action.
VB DataGrid11.aspx
<Columns>
<asp:HyperLinkColumn
DataNavigateUrlField="au_id"
DataNavigateUrlFormatString="datagrid13_details.aspx?id={0}"
Text="Get Details"
/>
</Columns>
</ASP:DataGrid>
On the details page, you retrieve the querystring argument and perform a join select to obtain details from the database. The
following sample demonstrates this scenario.
VB DataGrid13.aspx
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure
C# VB JScript
The following sample demonstrates a call to a stored procedure to fill the DataSet.
VB DataGrid14.aspx
VB DataGrid15.aspx
VB DataGrid16.aspx
VB DataGrid17.aspx
VB DataGrid18.aspx
VB XMLGen.aspx
Section Summary
1. The common language runtime's managed data access APIs abstract data and present it in a consistent way regardless
of its actual source (SQL Server, OLEDB, XML, and so on).
2. To give your page access to the classes you will need to perform SQL data access, you must import the System.Data
and System.Data.SqlClient namespaces into your page.
3. Populating a dataset from a SQL query involves creating a SqlConnection, associating a SqlDataAdapter object with
the connection that contains your query statement, and filling the dataset from the command.
4. The DataGrid control supports a DataSource property that takes an IEnumerable (or ICollection) type. You can
set this to the result of a SQL query by assigning the DataSet's DefaultView property, which is of type DataView.
5. The SqlDataAdapter maintains a Parameters collection that can be used to replace variable identifiers (denoted by an
"@" in front of the name) with values.
6. When performing commands that do not require data to be returned, such as inserts, updates, and deletes, you use a
SqlCommand instead of the SqlDataAdapter. The command is issued by calling an ExecuteNonQuery method,
which returns the number of rows affected.
7. The SqlConnection must be explicitly opened when you use the SqlCommand (the SqlDataAdapter automatically
handles opening the connection for you). Always remember to close the SqlConnection to the data model before the
page finishes executing. If you do not close the connection, you migh inadvertantly exhaust the connection limit while
waiting for the page instances to be released to garbage collection.
8. To allow rows to be edited, the DataGrid supports an integer EditItemIndex property, which indicates which row of
the grid should be editable. When this property is set, the DataGrid renders the row at that index as text input boxes
instead of simple labels.
9. The DataGrid exposes a DataKeyField property that you can set to the field name for the primary key. In the event
handler wired to the UpdateCommand, you can retrieve the key name from the DataGrid's DataKeys collection.
10. Using BoundColumn controls in the DataGrid gives you complete control over the order of the columns, as well as
their ReadOnly properties.
11. Using TemplateColumn controls in the DataGrid gives you complete control over the contents of the column.
12. The ButtonColumn control can be used to simply render a button control in each row for that column, which can be
associated with an event.
13. A HyperLinkColumn can be added to the DataGrid's Columns collection, which supports navigating to another page
when the link is clicked.
14. When the DataGrid's AllowSorting property is set to true, it renders hyperlinks for the column headers that fire a
Sort command back to the grid. You set the OnSortCommand property of the DataGrid to the handler you want to
call when the user clicks a column link.
15. The DataSet supports ReadXml, ReadXmlData, and ReadXmlSchema methods that take a FileStream as a
parameter, which can be used to populate a DataSet from an XML file.
16. Using stored procedures can reduce the cost of performing heavy database operations in an application.
Data Access and Customization
<ItemTemplate>
Hello <%# DataBinder.Eval(Container.DataItem, "name") %> !
</ItemTemplate>
</ASP:Repeater>
The Container represents the first control in the immediate hierarchy that supports the System.Web.UI.INamingContainer
marker interface. In this case, the Container resolves to an object of type System.Web.UI.WebControls.RepeaterItem,
which has a DataItem property. As the Repeater iterates over the DataSource collection, the DataItem contains the current
item in this collection. For example, if the data source is set to an ArrayList of Employee objects, the DataItem is of type
Employees. When bound to a DataView, the DataItem is of type DataRowView.
The following example demonstrates a Repeater control bound to a DataView (returned from a SQL query). HeaderTemplate
and FooterTemplate have also been defined and render at the beginning and end of the list, respectively.
VB DataList1.aspx
VB Datalist2.aspx
VB Datalist3.aspx
<ItemTemplate>
</ItemTemplate>
</ASP:DataList>
The following sample demonstrates this code in action. In the MyDataList_Select event handler, you populate several other
server controls with the details about the particular selected item.
VB Datalist4.aspx
[Run Sample] | [View Source]
Note that while the DataList recognizes a few special commands such as Select and Edit/Update/Cancel, the command
string fired inside a template can be any arbitrary string. For all commands, the DataList's OnItemCommand is fired. You can
wire this event to a handler as in the previous example; the following example shows how to do this.
<script runat="server">
</script>
<ItemTemplate>
</ItemTemplate>
</ASP:DataList>
C# VB JScript
Note that because more than one command can fire this event handler, you must employ a switch statement to determine the
particular command that was fired. The following sample demonstrates this code in action.
VB Datalist5.aspx
VB Datalist6.aspx
VB Datalist7.aspx
<script runat="server">
<ItemTemplate>
<asp:CheckBox id="Save" runat="server"/> <b>Save to Favorites</b>
</ItemTemplate>
</ASP:DataList>
C# VB JScript
The following sample demonstrates this code in action.
VB Datalist8.aspx
Section Summary
1. The DataList and Repeater controls provide developers fine-tuned control over the rendering of data-bound lists.
2. Rendering of bound data is controlled using a template, such as the HeaderTemplate, FooterTemplate, or
ItemTemplate.
3. The Repeater control is a general-purpose iterator, and does not insert anything in its rendering that is not contained
in a template.
4. The DataList control offers more control over the layout and style of items, and outputs its own rendering code for
formatting.
5. The DataList supports the Select, Edit/Update/Cancel, and Item Command events, which can be handled at the
page level by wiring event handlers to the DataList's Command events.
6. DataList supports a SelectedItemTemplate and EditItemTemplate for control over the rendering of a selected or
editable item.
7. Controls can be programmatically retrieved from a template using the Control.FindControl method. This should be
called on a DataListItem retrieved from the DataList's Items collection.
Web Forms Syntax Reference
C# VB JScript
VB Reference1.aspx
<%
...
number = subtract(number, 1)
...
%>
C# VB JScript
VB Reference2.aspx
C# VB JScript
VB Reference3.aspx
C# VB JScript
VB Reference4.aspx
items.Add("One")
items.Add("Two")
items.Add("Three")
MyList.DataSource = items
MyList.DataBind()
End Sub
C# VB JScript
Calling the DataBind method of a control causes a recursive tree walk from that control on down in the tree; the DataBinding
event is raised on each server control in that hierarchy, and data binding expressions on the control are evaluated accordingly.
So, if the DataBind method of the page is called, then every data binding expression within the page will be called.
VB Reference5.aspx
C# VB JScript
VB Reference6.aspx
<%--
<asp:calendar id="MyCal" runat=server/>
<% For I=0 To 44 %>
Hello World <br>
<% Next %>
--%>
C# VB JScript
VB Reference7.aspx
VB Reference8.aspx