Tải bản đầy đủ (.pdf) (10 trang)

Professional ASP.NET 3.5 in C# and Visual Basic Part 17 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (288.57 KB, 10 trang )

Evjen c03.tex V2 - 01/28/2008 12:33pm Page 114
Chapter 3: ASP.NET Web Server Controls
{
Response.Write("OnTextChanged event triggered");
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("OnClick event triggered");
}
<
/script
>
As you build and run this page, notice that you can type something in the text box, but once you tab out
of it, the
OnTextChanged
event is triggered and the code contained in the
TextBox1_TextChanged
event
runs.Tomakethiswork,youmustaddthe
AutoPostBack
attribute to the TextBox control and set it to
True
. This causes the Web page to look for any text changes prior to an actual page postback. For the
AutoPostBack
feature to work, the browser viewing the page must support ECMAScript.
Using AutoCompleteType
You want the forms you build for your Web applications to be as simple to use as possible. You want to
make them easy and quick for the end user to fill out the information and proceed. If you make a form
too onerous, the people who come to your site may leave without completing it.
One of the great capabilities for any W eb form is smart auto-completion. You may have seen this yourself
when you visited a site for the first time. As you start to fill out information in a form, a drop-down list


appears below the text box as you type, showing you a value that you have typed in a previous form.
The plain text box you were working with has become a smart text box. Figure 3-5 shows an example of
this feature.
Figure 3-5
A great new aspect of the TextBox control is the
AutoCompleteType
attribute, which enables you to
apply the auto-completion feature to your own forms. You have to help the text boxes on your form to
recognize the type of information that they should be looking for. What does that mean? Well, first look
at the possible values of the
AutoCompleteType
attribute:
BusinessCity Disabled HomeStreetAddress
BusinessCountryRegion DisplayName HomeZipCode
BusinessFax Email JobTitle
BusinessPhone FirstName LastName
BusinessState Gender MiddleName
BusinessStateAddress HomeCity None
BusinessUrl HomeCountryRegion Notes
BusinessZipCode HomeFax Office
Cellular Homepage Pager
Company HomePhone Search
Department HomeState
114
Evjen c03.tex V2 - 01/28/2008 12:33pm Page 115
Chapter 3: ASP.NET Web Server Controls
From this list, you can see that if your text box is asking for the end user’s home street address, you want
to use the following in your TextBox control:
<
asp:TextBox ID="TextBox1" runat="server"

AutoCompleteType="HomeStreetAddress"
><
/asp:TextBox
>
As you view the source of the text box you created, you can see that the following construction has
occurred:
<
input name="TextBox1" type="text" vcard_name="vCard.Home.StreetAddress"
id="TextBox1" /
>
This feature makes your forms easier to work with. Yes, it is a simple thing, but sometimes it is the little
things that keep the viewers coming back again and again to your Web site.
The Button Ser ver Control
Another common control for your Web forms is a button that can be constructed using the Button server
control. Buttons are the usual element used to submit forms. Most of the time you are simply dealing with
items contained in your forms through the Button control’s
OnClick
event, as illustrated in Listing 3-5.
Listing 3-5: The Button control’s OnClick event
VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
’ Code here
End Sub
C#
protected void Button1_Click(object sender, EventArgs e)
{
// Code here
}
The Button control is one of the easier controls to use, but there are a couple of properties of which you
must be aware:

CausesValidation
and
CommandName
. They are discussed in the following sections.
The CausesValidation Property
If you have more than one button on your Web page and you are working with the validation server con-
trols, you may not want to fire the validation for each button on the form. Setting the
CausesValidation
property to
False
is a w ay to use a button that will not fire the validation process. This is explained in
more detail in Chapter 4.
The CommandName Property
You can have multiple buttons on your form all working from a single event. The nice thing is that you
can also tag the buttons so that the code can make logical decisions based on which button on the form
115
Evjen c03.tex V2 - 01/28/2008 12:33pm Page 116
Chapter 3: ASP.NET Web Server Controls
was clicked. You must construct your Button controls in the manner illustrated in Listing 3-6 to take
advantage of this behavior.
Listing 3-6: Constructing multiple Button controls to work from a single function
<
asp:Button ID="Button1" runat="server" Text="Button 1"
OnCommand="Button_Command" CommandName="DoSomething1" /
>
<
asp:Button ID="Button2" runat="server" Text="Button 2"
OnCommand="Button_Command" CommandName="DoSomething2" /
>
Looking at these two instances of the Button control, you should pay attention to several things. The

first thing to notice is what is not present — any attribute mention of an
OnClick
event. Instead, you
use the
OnCommand
event, which points to an event called
Button_Command
. You can see that both Button
controls are working from the same event. How does the event differentiate between the two buttons
being clicked? Through the value placed in the
CommandName
property. In this case, they are indeed
separate values —
DoSomething1
and
DoSomething2
.
The next step is to create the
Button_Command
event to deal with both these buttons by simply typing one
out or by selecting the
Command
event from the drop-down list of available events for the Button control
from the code view of Visual Studio. In either case, you should end up with an event like the one shown
in Listing 3-7.
Listing 3-7: The Button_Command event
VB
Protected Sub Button_Command(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.CommandEventArgs)
Select Case e.CommandName

Case "DoSomething1"
Response.Write("Button 1 was selected")
Case "DoSomething2"
Response.Write("Button 2 was selected")
End Select
End Sub
C#
protected void Button_Command(Object sender,
System.Web.UI.WebControls.CommandEventArgs e)
{
switch (e.CommandName)
{
case("DoSomething1"):
Response.Write("Button 1 was selected");
break;
case("DoSomething2"):
Response.Write("Button 2 was selected");
break;
}
}
116
Evjen c03.tex V2 - 01/28/2008 12:33pm Page 117
Chapter 3: ASP.NET Web Server Controls
Notice that this method uses
System.Web.UI.WebControls.CommandEventArgs
instead of the typical
System.EventArgs
. This gives you access to the member
CommandName
used in the

Select Case
(
switch
)
statement as
e.CommandName
. Using this object, you can check for the value of the
CommandName
property
used by the button that was clicked on the form and take a specific action based upon the value passed.
You can add some parameters to be passed in to the
Command
event beyond what is defined in the
Com-
mandName
property. You do this by using the Button control’s
CommandArgument
property. Adding values
to the property enables you to define items a bit more granularly if you want. You can get at this value
via server-side code using
e.CommandArgument
from the
CommandEventArgs
object.
Buttons That Work with Client-Side JavaScript
Buttons are frequently used f or submitting information and causing actions to occur on a Web page.
Before ASP.NET 1.0/1.1, people intermingled quite a bit of JavaScript in their pages to fire JavaScript
events when a button was clicked. The process became more cumbersome in ASP.NET 1.0/1.1, but ever
since ASP.NET 2.0, it is much easier.
You can create a page that has a JavaScript event, as well as a server-side event, triggered when the

button is clicked, as illustrated in Listing 3-8.
Listing 3-8: Two types of events for the button
VB
<
%@ Page Language="VB" %
>
<
script runat="server"
>
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Response.Write("Postback!")
End Sub
<
/script
>
<
script language="javascript"
>
function AlertHello()
{
alert(’Hello ASP.NET’);
}
<
/script
>
<
html xmlns=" />>
<
head runat="server"

>
<
title
>
Button Server Control
<
/title
>
<
/head
>
<
body
>
<
form id="form1" runat="server"
>
<
asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="AlertHello()" OnClick="Button1_Click" /
>
<
/form
>
Continued
117
Evjen c03.tex V2 - 01/28/2008 12:33pm Page 118
Chapter 3: ASP.NET Web Server Controls
<
/body

>
<
/html
>
C#
<
%@ Page Language="C#" %
>
<
script runat="server"
>
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Postback!");
}
<
/script
>
The first thing to notice is the new attribute for the Button server control:
OnClientClick
. It points to the
client-side function, unlike the
OnClick
attribute that points to the server-side event. T his example uses
a JavaScript function called
AlertHello()
.
One cool thing a bout Visual Studio 2008 is that it can work with server-side script tags that are right
alongside client-side script tags. It all works together seamlessly. In the example, after the JavaScript alert
dialog is issued (see Figure 3-6) and the end user clicks OK, the page posts back as the server-side event

is triggered.
Figure 3-6
Another interesting attribute for the button controls is
PostBackUrl
. It enables you to perform cross-page
posting, instead of simply posting your ASP.NET pages back to the same page, as shown in the following
example:
<
asp:Button ID="Button2" runat="server" Text="Submit page to Page2.aspx"
PostBackUrl="Page2.aspx" /
>
Cross-page posting is covered in greater detail in Chapter 1.
118
Evjen c03.tex V2 - 01/28/2008 12:33pm Page 119
Chapter 3: ASP.NET Web Server Controls
The LinkButton Server Control
The LinkButton server control is a variation of the Button control. It is the same except that the LinkButton
control takes the form of a hyperlink. Nevertheless, it is not a typical hyperlink. When the end user clicks
the link, it behaves like a button. This is an ideal control to use if you have a large number of buttons on
your Web form.
A LinkButton server control is constructed as follows:
<
asp:LinkButton ID="LinkButton1" Runat="server" OnClick="LinkButton1_Click"
>
Submit your name to our database
<
/asp:LinkButton
>
Using the LinkButton control gives you the results shown in Figure 3-7.
Figure 3-7

The ImageButton Ser ver Control
The ImageButton control is also a variation of the Button control. It is almost exactly the same as the
Button control except that it enables you to use a custom image as the form’s button instead of the typical
buttons used on most forms. This means that you can create your own buttons as images and the end
users can click the images to submit form data. A typical construction of the ImageButton is as follows:
<
asp:ImageButton ID="ImageButton1" runat="server"
OnClick="ImageButton1_Click" ImageUrl="MyButton.jpg" /
>
The ImageButton control specifies the location of the image used by using the
ImageUrl
property. From
this example, you can see that the
ImageUrl
points to
MyButton.jpg
. The big difference between the
ImageButton control and the LinkButton or Button controls is that ImageButton takes a different con-
struction for the
OnClick
event. It is shown in Listing 3-9.
Listing 3-9: The Click event for the ImageButton control
VB
Protected Sub ImageButton1_Click(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.ImageClickEventArgs)
Continued
119
Evjen c03.tex V2 - 01/28/2008 12:33pm Page 120
Chapter 3: ASP.NET Web Server Controls
’ Code here

End Sub
C#
protected void ImageButton1_Click(object sender,
System.Web.UI.WebControls.ImageClickEventArgs e)
{
// Code here
}
The construction uses the
ImageClickEventArgs
object instead o f the
System.EventArgs
object usually
used with the LinkButton and Button controls. You can use this object to determine where in the image
the end user clicked by using both
e.X
and
e.Y
coordinates.
The Search and Play Video buttons on the page shown in Figure 3-8 are image buttons.
Figure 3-8
The HyperLink Ser ver Control
The HyperLink server control enables you to programmatically work with any hyperlinks on your Web
pages. Hyperlinks are links that allow end users to transfer from one page to another. You can set the
text of a hyperlink using the control’s
Text
attribute:
120
Evjen c03.tex V2 - 01/28/2008 12:33pm Page 121
Chapter 3: ASP.NET Web Server Controls
<

asp:HyperLink ID="HyperLink1" runat="server" Text="Go to this page here"
NavigateUrl="~/Default2.aspx"
><
/asp:HyperLink
>
This server control creates a hyperlink on your page with the text
Go to this page here
. When the link
is clicked, the user is redirected to the value that is placed in the
NavigateUrl
property (in this case, the
Default2.aspx
page).
The interesting thing about the HyperLink server control is that it can be used for images as well as text.
Instead of using the
Text
attribute, it uses the
ImageUrl
property:
<
asp:HyperLink ID="HyperLink1" runat="server" ImageUrl="~/MyLinkImage.gif"
NavigateUrl="~/Default2.aspx"
><
/asp:HyperLink
>
The HyperLink control is a great way to dynamically place hyperlinks on a Web page based either upon
user input in a form or on database values that are retrieved when the page is loaded.
The DropDownList Ser ver Control
The DropDownList server control enables you to place an HTML select box on your Web page and
program against it. It is ideal when you have a large collection of items from which you want the end

user to select a single item. It is usually used for a medium- to large-sized collection. If the collection size
is relatively small, consider using the RadioButtonList server control (described later in this chapter).
The select box generated by the DropDownList control displays a single item and allows the end user to
make a selection from a larger list of items. Depending on the number of choices available in the select
box, the end user may have to scroll through a list of items. Note that the appearance of the scroll bar in
the drop-down list is automatically created by the browser depending on the browser version and the
number of items contained in the list.
Here is the code for DropDownList control:
<
asp:DropDownList ID="DropDownList1" runat="server"
>
<
asp:ListItem
>
Car
<
/asp:ListItem
>
<
asp:ListItem
>
Airplane
<
/asp:ListItem
>
<
asp:ListItem
>
Train
<

/asp:ListItem
>
<
/asp:DropDownList
>
This code generates a drop-down list in the browser, as shown in Figure 3-9.
Figure 3-9
The DropDownList control comes in handy when you start binding it to various data stores. The data
stores can either be arrays, database values, XML file values, or values found elsewhere. For an example
121
Evjen c03.tex V2 - 01/28/2008 12:33pm Page 122
Chapter 3: ASP.NET Web Server Controls
of binding the DropDownList control, this next example looks at dynamically generating a DropDown-
List control from one of three available arrays, as shown in Listing 3-10.
Listing 3-10: Dynamically generating a DropDownList control from an array
VB
<
%@ Page Language="VB" %
>
<
script runat="server"
>
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs)
Dim CarArray() As String = {"Ford", "Honda", "BMW", "Dodge"}
Dim AirplaneArray() As String = {"Boeing 777", "Boeing 747", "Boeing 737"}
Dim TrainArray() As String = {"Bullet Train", "Amtrack", "Tram"}
If DropDownList1.SelectedValue = "Car" Then
DropDownList2.DataSource = CarArray
ElseIf DropDownList1.SelectedValue = "Airplane" Then

DropDownList2.DataSource = AirplaneArray
Else
DropDownList2.DataSource = TrainArray
End If
DropDownList2.DataBind()
DropDownList2.Visible = True
End Sub
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Response.Write("You selected
<
b
>
"&_
DropDownList1.SelectedValue.ToString() & ": " & _
DropDownList2.SelectedValue.ToString() & "
<
/b
>
")
End Sub
<
/script
>
<
html xmlns=" />>
<
head runat="server"
>
<

title
>
DropDownList Page
<
/title
>
<
/head
>
<
body
>
<
form id="form1" runat="server"
>
<
div
>
Select transportation type:
<
br /
>
<
asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="true"
>
<
asp:ListItem
>

Select an Item
<
/asp:ListItem
>
<
asp:ListItem
>
Car
<
/asp:ListItem
>
<
asp:ListItem
>
Airplane
<
/asp:ListItem
>
<
asp:ListItem
>
Train
<
/asp:ListItem
>
<
/asp:DropDownList
>
&nbsp;
<

asp:DropDownList ID="DropDownList2" runat="server" Visible="false"
>
122
Evjen c03.tex V2 - 01/28/2008 12:33pm Page 123
Chapter 3: ASP.NET Web Server Controls
<
/asp:DropDownList
>
<
asp:Button ID="Button1" runat="server" Text="Select Options"
OnClick="Button1_Click" /
>
<
/div
>
<
/form
>
<
/body
>
<
/html
>
C#
<
%@ Page Language="C#" %
>
<
script runat="server"

>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] CarArray = new string[4] {"Ford", "Honda", "BMW", "Dodge"};
string[] AirplaneArray = new string[3] {"Boeing 777", "Boeing 747",
"Boeing 737"};
string[] TrainArray = new string[3] {"Bullet Train", "Amtrack", "Tram"};
if (DropDownList1.SelectedValue == "Car") {
DropDownList2.DataSource = CarArray; }
else if (DropDownList1.SelectedValue == "Airplane") {
DropDownList2.DataSource = AirplaneArray; }
else {
DropDownList2.DataSource = TrainArray;
}
DropDownList2.DataBind();
DropDownList2.Visible = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("You selected
<
b
>
"+
DropDownList1.SelectedValue.ToString() + ": " +
DropDownList2.SelectedValue.ToString() + "
<
/b
>
");

}
<
/script
>
In this example, the second drop-down list is dynamically generated based upon the value selected from
the first drop-down list. For instance, selecting
Car
from the first drop-down list dynamically creates a
second drop-down list on the form that includes a list of available car selections.
This is possible because of the use of the
AutoPostBack
feature of the
DropDownList
control. When the
AutoPostBack
property is set to
True
, the method provided through the
OnSelectedIndexChanged
event
is fired when a selection is made. In the example, the
DropDownList1_SelectedIndexChanged
event is
fired, dynamically creating the second drop-down list.
In this method, the content of the second drop-down list is created in a string array and then bound to the
second DropDownList control through the use of the
DataSource
property and the
DataBind()
method.

When built and run, this page looks like the one shown in Figure 3-10.
123

×