1. Trang chủ
  2. » Công Nghệ Thông Tin

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

10 512 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 288,57 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Listing 3-5: The Button control’s OnClick event VB Protected Sub Button1_ClickByVal sender As Object, ByVal e As System.EventArgs ’ Code here End Sub C# protected void Button1_Clickobjec

Trang 1

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, theOnTextChangedevent is triggered and the code contained in theTextBox1_TextChangedevent

runs To make this work, you must add theAutoPostBackattribute 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

AutoPostBackfeature 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 Web 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 theAutoCompleteTypeattribute, 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 theAutoCompleteTypeattribute:

Trang 2

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’sOnClickevent, 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:CausesValidationandCommandName 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 theCausesValidation

property toFalseis a way 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

Trang 3

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 anOnClickevent Instead, you

use theOnCommandevent, which points to an event calledButton_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 theCommandNameproperty In this case, they are indeed

separate values —DoSomething1andDoSomething2

The next step is to create theButton_Commandevent to deal with both these buttons by simply typing one

out or by selecting theCommandevent 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;

}

}

Trang 4

Notice that this method usesSystem.Web.UI.WebControls.CommandEventArgsinstead of the typical

System.EventArgs This gives you access to the memberCommandNameused in theSelect Case(switch) statement ase.CommandName Using this object, you can check for the value of theCommandNameproperty 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 theCommandevent beyond what is defined in the Com-mandNameproperty You do this by using the Button control’sCommandArgumentproperty 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 usinge.CommandArgumentfrom theCommandEventArgsobject

Buttons That Work with Client-Side JavaScript

Buttons are frequently used for 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="http://www.w3.org/1999/xhtml">

<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

Trang 5

</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 theOnClickattribute that points to the server-side event This example uses

a JavaScript function calledAlertHello()

One cool thing about 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 isPostBackUrl 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

Trang 6

The LinkButton Ser ver 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 theImageUrlproperty From this example, you can see that theImageUrlpoints toMyButton.jpg The big difference between the

ImageButton control and the LinkButton or Button controls is that ImageButton takes a different

con-struction for theOnClickevent 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

Trang 7

’ Code here

End Sub

C#

protected void ImageButton1_Click(object sender,

System.Web.UI.WebControls.ImageClickEventArgs e)

{

// Code here

}

The construction uses theImageClickEventArgsobject instead of theSystem.EventArgsobject 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 bothe.Xande.Ycoordinates

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’sTextattribute:

Trang 8

<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 textGo to this page here When the link

is clicked, the user is redirected to the value that is placed in theNavigateUrlproperty (in this case, the

Default2.aspxpage)

The interesting thing about the HyperLink server control is that it can be used for images as well as text Instead of using theTextattribute, it uses theImageUrlproperty:

<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

Trang 9

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 DropDown-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="http://www.w3.org/1999/xhtml">

<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">

Trang 10

<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, selectingCarfrom 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 theAutoPostBackfeature of theDropDownListcontrol When the

AutoPostBackproperty is set toTrue, the method provided through theOnSelectedIndexChangedevent

is fired when a selection is made In the example, theDropDownList1_SelectedIndexChangedevent 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 theDataSourceproperty and theDataBind()method When built and run, this page looks like the one shown in Figure 3-10

Ngày đăng: 05/07/2014, 18:20

TỪ KHÓA LIÊN QUAN