Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ASP.NET 2

.0.pdf
Скачиваний:
19
Добавлен:
17.08.2013
Размер:
24.67 Mб
Скачать

Events and Code

Protected tells you about who can use the procedure. In this case it means that only other programs within the same class can use this procedure. You don’t need to worry about this for now; Chapter 9 looks at this in more detail.

Sub tells you that this is a subroutine, and that it doesn’t return a value. That means ASP.NET can simply call this and not expect anything back.

Page_Load is the name of the event procedure. The name of event procedures can be anything, but you’ll find certain standard usages appearing that are descriptive of the actual event. The Page_Load event is very descriptive because this event procedure will be used whenever

the page is loaded into ASP.NET for processing.

Next you have the middle section; these are the parameters. There are two parameters, separated from each other by a comma:

ByVal sender As Object, ByVal e As System.EventArgs

The parameters are simply variables that get passed into the event procedure by ASP.NET. Chapter 9 covers variables in more detail, so the actual syntax isn’t explained here, but some details are worth knowing. By and large all events in ASP.NET have two parameters. The first, typically called sender, is the object that raised the event. In this case it is the actual page, because the page is saying “Hey, I’ve loaded and you can do your stuff now.” For other events, such as those that buttons raise, the sender would be the button. The second parameter, e, is any additional information that the event procedure might need. For the Page_Load event there is no additional information, but later in the chapter you’ll look at events where you do need some extra detail. Neither of these arguments is needed for your event procedure, but they are provided by ASP.NET in case they are required.

The last part of the event procedure indicates which event the procedure is handling:

Handles Me.Load

This is how you actually hook into the event handling. When the page loads it raises its Load event, and any procedure that handles that event will be called. If you didn’t have this Handles statement, Page_Load would simply be a procedure, not an event procedure. So it’s not the name of the procedure that’s important, it’s the Handles keyword and the name of the actual event; they tell ASP.NET that when the Load event of the page is raised, this procedure should be run. The use of Me simply indicates the current page.

Now that you’ve actually hooked your procedure into the event handling system of ASP.NET, you can run your own code:

Label1.Text = “You entered “ & TextBox1.Text

This line of code simply sets the text for the label to some static text plus whatever text was entered into the text box. Don’t worry too much about what the ampersand (&) means — Chapter 9 looks at that sort of thing in more detail.

189

Chapter 6

Here are the event procedures for the buttons:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

TextBox1.Text = “You clicked button 1” End Sub

The declaration is very similar to the Page_Load one, apart from the name of the procedure and the event being handled. This time the event is the Click event on the button. Within the event procedure you simply set the text of the text box. The event procedure for the second button is similar, but with the obvious changes of the names and text.

Now look at what happens when the examples are run. When the page is first loaded, the Page_Load event procedure runs and the text for the label is set. However, because there is no text in the text box, the label only has “You entered” as its text. When you enter some text into the text box and click the first button, the page is loaded again, so the Page_Load event procedure is run, followed by the Button1_Click event procedure. So the text you entered into the text box is displayed in the label, and

then the text box has new text set from within the Button1_Click event procedure. The important thing to note is that both event procedures run; the Page_Load event procedure will always be before event procedures for controls on the page.

This process is repeated as you continue to click the buttons.

The Postback Architecture

One of the problems you might have spotted is that the Page_Load event always runs, even when a button is clicked. There may be times when you want code to run when the page is first loaded, but not when buttons are clicked. For example, consider the previous example, where you displayed the contents of a text box in a label. When the page first loaded there was nothing in the text box so your label text was incomplete. The next Try It Out corrects this.

Try It Out

Checking for Postback

1.If you are still running the browser from the previous example, close it.

2.In Visual Web Developer, change the Page_Load event procedure so that it looks like this:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Page.IsPostBack Then

Label1.Text = “You entered “ & TextBox1.Text

End If

End Sub

3.Save the page and press F5 to run it. Notice that the label text is label — this is the default text for a Label control and you didn’t change it when you placed the Label on the page. Enter some text and click a button, and you’ll see that the label now has text. Close the browser.

4.Now change the Page_Load event to this:

190

Events and Code

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Page.IsPostBack Then

Label1.Text = “You entered “ & TextBox1.Text

Else

Label1.Text = “Enter some text and press a button”

End If

End Sub

5.Save the page and press F5 to run it. Now you have this more useful, new text when the page first loads, and different text when a button is pressed.

How It Works

Having different text at the first page load from subsequent page loads works because the ASP.NET page has a property called IsPostBack, which identifies whether or not the page has been posted back to — that is, whether a button has been pressed. If so, IsPostBack will be true. If it’s the first time the page has loaded — that is, a button has not been pressed — IsPostBack will be false.

In the first code change you only displayed text if IsPostBack was true — if a button had been pressed. The second code change had different text for the two different situations.

It is important to know that this postback design only works when you are dealing with a single page, because IsPostBack gets reset when you move to another page. Consider two pages, Page1 and Page2, each with a Page_Load event procedure and a Button1_Click event procedure for a button. They also have a hyperlink to each other, allowing you to jump between the pages. You start with Page1, the Page_Load event procedure runs, and IsPostBack is false. You press the button and the Page_Load event is run again, followed by the Button1_Click event; in both event procedures IsPostBack would be True. You click the link to jump to Page2 and the Page_Load event procedure on that page runs, and IsPostBack in the Page_Load event on Page2 is False. Now you click the link to jump directly back to Page1, where the Page_Load event runs once more, but this time IsPostBack is False as well. The use of IsPostBack only works when you remain on the same page, so don’t think that “the first time the page is loaded” means the very first time. The following table might help to make this clear.

Action

Page

Control

Events

IsPostBack

 

 

 

 

 

Page loads

Page1

 

Page_Load

False

Button clicked

Page1

Button1

Page_Load

True

 

 

 

Button1_Click

 

Navigate to Page 2

Page2

 

Page_Load

False

Navigate to Page 1

Page1

 

Page_Load

False

What Events Are Available?

In the first example in this chapter you created event procedures in different ways: by double-clicking the page and control, and by selecting the event from a drop-down list. The questions that might be

191

Chapter 6

poised on your lips are what events are there, how can I find the events, and which events should I use? Well, the first two questions can be answered in the same way, and there are several places to look.

In order to find out what events are available, you can use the code editor window in Visual Web Developer. The left-hand drop-down list shows the controls on the page, as well as an entry for the page itself. Selecting the page or a control causes the right-hand drop-down list to be filled with the events for the selected control (see Figure 6-14 — you can’t actually get both lists to drop down at once; we’ve done this to make it clearer to see). Selecting the event creates the empty event procedure, or shows the event procedure if it has already been created.

Figure 6-14

You can also use the Properties area on the page designer. Above the list of properties is an icon that looks like a lightning bolt; clicking this icon shows a list of events for the control, as shown in Figure 6-15. If you double-click in the space to the right of an event, the code window will be displayed and the event procedure created for you, or like the code window selection, you’ll be shown the event procedure if it already exists. By and large the events you’ll be interested in will be grouped under Action or Data.

Figure 6-15

The other place to find a list of events is in the Help files, where details of each event and what they are used for is listed.

192

Events and Code

Which Events Should I Use?

If you start looking into the events that are available you’ll soon realize that there are quite a few, and it’s not always obvious which ones should be used. The following table details some of the most common controls and events; this isn’t all of them, just the ones you’ll find most useful.

 

Control

Event

Is raised when . . .

 

 

 

 

 

Button

Click

The button is clicked.

 

LinkButton

 

 

 

ImageButton

 

 

 

DropDownList

SelectedIndexChanged

The selection on the list changes.

 

ListBox

 

This is useful for performing some

 

 

 

action based on the new selection.

 

CheckBox

CheckChanged

The status of the CheckBox or

 

RadioButton

 

RadioButton changes. That is, when

 

 

 

they either become checked or

 

 

 

unchecked.

 

CheckBoxList

SelectedIndexChanged

The selection on the list changes.

 

RadioButtonList

 

 

 

Calendar

SelectionChanged

The selected date is changed.

 

 

VisibleMonthChanged

The month is changed.

 

Login

Authenticate

The user is authenticated.

 

 

LoggedIn

The user has logged in.

 

 

LoginError

There is an error during the login process.

 

DataList

DataBound

An item is taken from a database and

 

 

 

bound to the list.

 

GridView

RowDeleting

The current row is being deleted.

 

 

RowUpdating

The current row is being updated.

 

 

SelectedIndexChanged

The selected row has changed.

 

SqlDataSource

Deleted

A row has been deleted from the set of

 

 

 

data.

 

 

Inserted

A row has been inserted into the set of

 

 

 

data.

 

 

Updated

A row has been updated in the set of

 

 

 

data.

 

Menu

MenuItemDataBound

An item is being bound to the menu.

 

 

 

 

193

Chapter 6

Some of these are fairly obvious in their usage. For example, you’ve already seen the Click event of the button, and you can see that all of the button type controls have that same event. So if you don’t want to have a standard button, but want to maybe have an image instead, you still use the Click event. Give this a try in the following Try It Out, but this time you’ll use a different method for hooking into the event.

Try It Out

Manually Creating Events

1.If you have a running browser window, close it, and open Default.aspx in Visual Web Developer.

2.Create a Regular Folder called Images under the web site. You can use the right-click Add Folder menu on the web site for this, as shown in Figure 6-16.

Figure 6-16

3.Copy AddToCart.gif from the Images folder of the Wrox United site and place it in the Images folder you have just created.

4.In Design View place an ImageButton on the form, and set the ImageUrl property to

~/images/AddToCart.gif.

5.Select the TextBox and change the Columns property from 0 to 50.

6.Switch to Source View and locate the ImageButton control. Change the declaration so that it looks like this:

<asp:ImageButton ID=”ImageButton1” runat=”server”

OnClick=”ImageButton_Click” ImageUrl=”~/images/AddToCart.gif” />

7.Open the code file, Default.aspx.vb, and add the following code, just before the End Class statement:

Protected Sub ImageButton_Click(ByVal sender As Object, _

ByVal e As System.Web.UI.ImageClickEventArgs) TextBox1.Text = “You clicked the ImageButton at position” & _

e.X.ToString() & “,” & e.Y.ToString()

End Sub

194

Events and Code

8.Press F5 to run the page. Click several times in the ImageButton, moving the cursor so that you click in a different position. Notice how the coordinates of where you click are shown in the text box.

How It Works

The important bit of how this works is in the Source View, where the ImageButton control is defined. Here you added the following to it:

OnClick=”ImageButton_Click”

This tells the control that for the Click event you want to run the procedure called ImageButton_Click. It says OnClick because that’s the convention for ASP.NET events. For each event there is usually a corresponding property that starts with On — this allows the events to be defined on the control as well as in the code. It’s just two ways of doing the same thing. For the standard Button controls you used Handles on the end of the event procedure declaration, but for the ImageButton you used the OnClick property to define the event procedure.

Within the code file, the event procedure declaration is similar, but the second parameter is different from the type you’ve seen before:

Protected Sub ImageButton_Click(ByVal sender As Object, _

ByVal e As System.Web.UI.ImageClickEventArgs)

For the Button, the second parameter was System.EventArgs, but for the ImageButton it is System.Web.UI.ImageClickEventArgs. Remember that the second parameter can be used by ASP.NET to pass extra information into the event procedure, but for Button controls there was no extra information. For an ImageButton there is extra information, so the parameter is different — in this case it contains the X and Y coordinates of where on the image the mouse was clicked. You simply display these coordinates in the text box. You don’t actually need these coordinates, but this is a great example of parameters having extra information.

A parameter name other than System.EventArgs is actually a good indication that additional information may be available to you in the event procedure. You can find out what that information is by simply typing e. in the code window and looking at the IntelliSense that pops up.

Events Aren’t Triggered by Users Only

So far in this chapter the events you’ve seen have been explicitly generated by the user, by way of clicking a button. Some events, however, are generated in other ways. Some are indirectly generated by the user, perhaps by way of updating some data, and others are generated directly by ASP.NET. You can use the events regardless of how they are generated, and in this section you see how you can do this.

You’re going to create some events from data in a database, and although data has not been covered yet, it’s the events that are important. First, have a look at the news items on the Wrox United site (see Figure 6-17), found under the About News menu item.

195

Chapter 6

Figure 6-17

Here you can see that not all of the news items have a picture. In the following Try It Out, you see how the news items can be customized, by responding to events generated by controls that fetch data. You’ll make sure that an image is only visible when there is a picture associated with the news item.

Try It Out

Data Events

1.Close any open browser windows.

2.In Visual Web Developer open the DataEvents.aspx file from the Chapter06 web site.

3.Right-click the mouse button anywhere on the page, and select View in Browser from the menu that appears. You’ll see a screen similar to Figure 6-18.

196

Events and Code

Figure 6-18

Notice that not all of the news items have images. For those that don’t there is a small image with a red cross in it, indicating that the image is missing; this is the default. You need to modify the page to use events, so that if there is no image for the news item, that red cross isn’t shown.

4.Close the browser and switch to Design View in Visual Web Developer.

5.Select the DataList control. There are only two controls on the page: SqlDataSource and DataList. The DataList control is bound to a database, so it shows Databound items — simply click anywhere on this control to select it.

6.From the Properties box, select the events and double-click into the ItemDataBound event. Don’t enter any text, just double-click, and this will open the code editor and create the empty event procedure for you.

197

Chapter 6

7.Add the following code in the empty event procedure:

Dim row As DataRowView

Dim img As Image

If e.Item.ItemType = ListItemType.Item Or _ e.Item.ItemType = ListItemType.AlternatingItem Then

row = DirectCast(e.Item.DataItem, DataRowView)

If row(“PictureUrl”).ToString().Trim() = “” Then

img = DirectCast(e.Item.FindControl(“NewsImage”), Image) img.Visible = False

End If

End If

8.Save the pages and switch back to the Design View of the page. Right-click the page and select the View in Browser menu item to view the page in the browser. Notice how the red cross images have disappeared.

How It Works

Before looking at the code you need to understand how HTML handles images. The image is created with an img tag, like so:

<img src=”ImageName.gif”></img>

When the browser receives this HTML it displays the image, or that red cross if the image isn’t found. When you use server controls for images, you use an Image control:

<asp:Image ImageUrl=”ImageName.gif” runat=”server” id=”Image1”></Image>

This renders the same HTML as the first example. So if there’s no physical file you get that red cross, which is exactly what’s happening on this page; you need some way to not show the red cross image if there’s no picture associated with the news story.

In the DataEvents.aspx page you use an Image server control, but the value for the ImageUrl property is fetched from a database. Databases are covered in the next two chapters, so it’s not important to know how this works just yet. The important point is to realize that as each row of data (a news item) is fetched from the database it is bound to the DataList, which means that there will be an item in the DataList for each row in the table fetched from the database. Each row of data contains different bits of the news: the title, the description, and what you’re really interested in for this example, the picture name. But not every news item has a picture, so you have to check to see if the database has a picture and if it doesn’t, you make the Image control invisible. Take a look at the code that makes this possible.

First, you have the ItemDataBound event itself:

Protected Sub DataList1_ItemDataBound(ByVal sender As Object,

ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList1.ItemDataBound

198