V- Acerca de la forma en que está organizado el
2- Función de los Sindicatos
Chapter 3: Using List Controls ...131 Chapter 4: Using Advanced Web Server Controls ...147 Chapter 5: Working with User Controls ...165
Chapter 1: Using Basic
Web Server Controls
In This Chapter
⻬Identifying features with labels
⻬Giving the user a place for input with text boxes
⻬Simplifying control with buttons
⻬Providing options with check boxes
⻬Offering choices with radio buttons
⻬Using pictures to start processes with image controls
C
ontrols are the building blocks of ASP.NET pages. In fact, about half of ASP.NET programming consists of dragging controls from the toolbox onto the page and tweaking the properties of the controls to get them just right.This chapter presents a basic subset of ASP.NET controls that you’ll use in many, if not most, of the applications you work on. In particular, you get a look at six different controls and how to use them: Label, TextBox, Button,
CheckBox, RadioButton, and Image. In addition, this chapter introduces an important feature called View State that’s available for all ASP.NET controls. All code listings used in this book are available for download at www.dummies. com/go/aspnetaiofd. In addition, although the code listing in this chapter is written in C#, the VB.NET version is available for download too.
Using Label Controls
A Labelcontrol displays text to identify a feature on a Web page. For exam- ple, the page in Figure 1-1 shows four Labelcontrols. The first provides
Using Label Controls
102
instructions for the user. The next two identify input fields the user should enter data into. The fourth label displays the result of a calculation.
The .aspxmarkup looks like this for the four labels shown in Figure 1-1:
<asp:Label ID=”Label1” runat=”server” Text=”Enter two numbers to add.” /> <asp:Label ID=”Label2” runat=”server”
Text=”First number:” Width=”110px” /> <asp:Label ID=”Label3” runat=”server”
Text=”Second number:” Width=”110px” /> <asp:Label ID=”lblResult” runat=”server”
Text=”The result is: “ />
The first two properties specified for these label controls are found in all ASP.NET controls. IDprovides a name for the control that you can use to refer to the control from your code. If you don’t plan on referring to a control in your code, you’ll probably leave the IDset to the default generated by Visual Studio when you drag the control from the toolbox to the page. But if you do plan on referring to the control in your code, you should change the
IDproperty to something more meaningful. In this example, I left the first three labels at their generated values (Label1, Label2, and Label3) but changed the IDof the fourth label to lblResult.
Labels
Figure 1-1:
A page with labels.
Book II Chapter 1 Using Basic W eb Ser ver Controls
Using TextBox Controls
103
The runatattribute is also required for all ASP.NET controls. It indicates that the control will run at the server rather than at the browser. Note that
serveris the only value you can code for the runatattribute.
To set the text that’s displayed by a label, you use the Textproperty. You can set the Textproperty in the .aspxmarkup file by using the Textattribute, as each of the four controls in this example do. You can also set the Text
property in code. Here’s what that looks like:
lblResult.Text = “The result is: “ + answer.ToString();
The Labelcontrol also includes many other properties that let you control the way the label and its text will appear. For example, you can change the color, font, or size of the label. You can also specify the width of the label by using the Widthproperty. This property is useful because it lets you line up text boxes or other controls that are associated with labels. For example, the two text boxes shown in Figure 1-1 line up because the Widthproperty of the labels next to them are both set to 110.
The Textproperty of a Labelcontrol can include HTML tags. Then, the HTML tags are used to format the text displayed by the label. For example, you can display text in bold by using the <b>tag, like this:
Label1.Text = “Have a <b>great</b> day!”;
Here the word greatis displayed in boldface.
Using TextBox Controls
A TextBoxcontrol provides a way for users to enter text data. For example, Figure 1-2 shows a page that features two text box controls. The user can use these text boxes to enter a username and password. Notice that when the user enters data into the second text box, the data isn’t displayed; instead, dots are displayed to hide the data entered by the user (a common require- ment for password-entry fields).
The .aspxmarkup for these two text boxes is as follows:
<asp:TextBox ID=”txtName” runat=”server” /> <asp:TextBox ID=”txtPassword” runat=”server”
TextMode=”Password” />
Here, you can see that TextModehas been set to Passwordfor the second text box.
Using TextBox Controls
104
The following table lists the properties you’re most likely to use with a
TextBoxcontrol:
Property Description
ID The ID of the control.
Runat Must specify Runat=”Server”. Text The text displayed by the control.
TextMode SingleLine(the default), MultiLine, or Password.
Wrap Trueto automatically wrap long lines.
Columns Sets the width of the text box. Rows Sets the height of the text box.
MaxLength Sets the maximum number of characters the text box will accept. ReadOnly If true, the text box is read-only.
To create a multiline text box, set the TextModeproperty to MultiLine. Then, the text box will accept more than one line of input. Then you can use the Rowsproperty to specify the height of the text box. You may also want to set the Wrapproperty to Trueso text that goes beyond the width of the text box will wrap automatically. Here is markup that’s typical for a multiline text box:
<asp:TextBox ID=”txtDescription” runat=”server” TextMode=”MultiLine” Rows=”5” Wrap=”True” /> Text boxes Figure 1-2: A page with two text boxes.
Book II Chapter 1 Using Basic W eb Ser ver Controls
Using Button Controls
105
You can also use the Textproperty to retrieve data entered by the user. The
Textproperty is a string value, so you’ll need to convert it to an appropriate type if the value represents a number. For example, here’s how to convert text input to a decimal value in C#:
decimal amount = Decimal.Parse(txtAmount.Text);
In VB.NET, the code would look like this:
Dim Amount As Decimal
Amount = Decimal.Parse(txtAmount.Text)
In both cases, the conversion will throw an exception if the user doesn’t enter a valid number. So you’ll need to put the conversion inside a trystate- ment. For more on exceptions, see Book 4 for C# and Book 5 for Visual Basic. (Note that you can also avoid the exception by using a validation control as described in the next chapter.)
Using Button Controls
ASP.NET provides three distinct types of Buttoncontrols: Button, Link Button, and ImageButton. These three types of buttons have the same behavior, but they each have a different appearance. A standard Button
control looks like a regular button that the user can click. A LinkButton
Understanding view state
All ASP.NET server controls have a feature called view state that maintains the state of the control’s properties between round trips to and from the server. By default, view state is main- tained for all controls.
Whenever a program changes the value of a control property, the property value is written to a special hidden field called ViewState. This field is sent to the browser. Then, when the user posts the page back to the server, the ViewStatefield is sent back to the server and used to set property values to their previous settings.
For example, suppose you change the Text property of a Labelcontrol. Then the value
you set the Textproperty to will be included in the ViewStatefield. That way, when the page is sent back to the server, the value you set will be restored.
View state is enabled by default, but you can disable it for a control by specifying Enable ViewState=”False” for the control. You should disable view state in two situations:
✦ When you have changed the value of a property, but you want the property to be restored to its default value (or the value you specified in the .aspxfile) at the next round trip.
✦ When the page will not be posted back to itself.
Using Button Controls
106
looks like a hyperlink, and an ImageButtondisplays an image file, so its appearance depends entirely on the content of the image file. Figure 1-3 shows a Web page with a button of each type.
Here is the markup for the three buttons shown in Figure 1-3:
<asp:Button ID=”Button1” runat=”server” Text=”Add To Cart” />
<asp:LinkButton ID=”LinkButton1” runat=”server” Text=”Add To Cart” />
<asp:ImageButton ID=”ImageButton1” runat=”server” ImageUrl=”~/cart.gif” />
Note that the Textproperty for a LinkButtoncontrol can also be specified as content that appears between the start and end tags, like this:
<asp:LinkButton ID=”LinkButton1” runat=”server” > Add To Cart
</asp:LinkButton>
Either method is an acceptable way to code a LinkButton.
Because the purpose of a button is to allow the user to click it, normally a button control has an event handler for the Clickevent associated with it. In C#, you use the OnClickattribute to specify the event handler, like this:
<asp:Button ID=”Button1” runat=”server”
Text=”Add To Cart” OnClick=”Button1_Click” />
Here the method named Button1_Clickwill be called when the button is clicked.
In Visual Basic, you specify a Handlesclause on the Substatement for the procedure that handles the event. Here’s an example:
Figure 1-3:
A page with three buttons.
Book II Chapter 1 Using Basic W eb Ser ver Controls
Using CheckBox Controls
107
Protected Sub Button1_Click (sender As Object, _ e As EventArgs) Handles Button1.Click
Then, you don’t need to specify the OnClickattribute in the .aspxfile. (You can use OnClickin VB.NET if you prefer, but it’s more common to use Handles.)
Here are a few other things you should know about button controls:
✦ The page is automatically posted back to the server when the user clicks a button.
✦ For an ImageButtoncontrol, the eargument that’s passed to the event handler includes the X and Y coordinates of the point within the button image where the user clicked.In some cases, you may need to use this information to determine what part of the button image the user clicked.
✦ In addition to the Clickevent, buttons also raise a Commandevent if the CommandNameproperty has been set for the button.Then the e
argument includes the CommandNameproperty of the button that was clicked. This feature of button controls can come in handy when you want to use a single event handler for several buttons.
Using CheckBox Controls
A check box is a control that the user can click to either check or uncheck. Normally check boxes are used to let the user specify Yes or No to an option. Figure 1-4 shows a page with three check boxes.
Here’s the markup I used to create these three check boxes:
<asp:CheckBox ID=”chkPepperoni” runat=”server” Text=”Pepperoni” />
Figure 1-4:
A page with three check boxes.
Using CheckBox Controls
108
<asp:CheckBox ID=”chkMushrooms” runat=”server” Text=”Mushrooms” />
<asp:CheckBox ID=”chkAnchovies” runat=”server” Text=”Anchovies” />
By default, a check box is initially unchecked. To make a check box checked when it’s initially displayed, set its Checkedproperty to True. For example, here’s how you can suggest Anchoviesto your customers:
<asp:CheckBox ID=”chkAnchovies” runat=”server” Text=”Anchovies” Checked=”True” />
Checking the Checked property
Usually check box controls do not cause a postback when they are clicked. The most common way to deal with check boxes in your code is to check their status in the Page_Loadmethod or in another event handler, such as the handler for the Clickevent of a button. Here’s a Page_Loadmethod that uses the Checkedproperty of the three check boxes on the page, and then sets the Textproperty of a label to indicate which toppings were ordered:
protected void Page_Load(object sender, EventArgs e) { String order = “”; if (chkPepperoni.Checked) order += “Pepperoni<br>”; if (chkMushrooms.Checked) order += “Mushrooms<br>”; if (chkAnchovies.Checked) order += “Anchovies<br>”; lblOrder.Text = order; }
Figure 1-5 shows how the page appears after the user has selected two of the check boxes and clicked the Order Pizzabutton.
Figure 1-5:
Confirming a pizza order.
Book II Chapter 1 Using Basic W eb Ser ver Controls
Using CheckBox Controls
109
For you Visual Basic programmers, here’s the equivalent code in VB.NET:
Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) _
Handles Me.Load Dim Order As String = “” If chkPepperoni.Checked Then
Order &= “Pepperoni<br>” End If
If chkMushrooms.Checked Then Order &= “Mushrooms<br>” End If
If (chkAnchovies.Checked) Then Order &= “Anchovies<br>” End If
lblOrder.Text = Order End Sub
Another way to check the Checked property
If you prefer, you can provide an event handler for the CheckChangedevent method of a check box, which is raised when the user clicks the check box. Note, however, that clicking a check box doesn’t usually cause a postback. As a result, the page won’t actually be submitted to the server until the user clicks a button or other control that doescause a postback. Then the
CheckChangedevent handler can be called — after the Page_Loadmethod but before the handler for the event that caused the page to be posted. Listing 1-1 shows a C# version of a code-behind file that handles the
CheckChangedevents for the pizza-order check boxes. As you can see, the
CheckChangedevent for each check box sets a booleanvariable that indicates whether the item has been ordered. Then, the Clickevent for the btnOrder Pizzabutton uses these booleanvariables to determine which items have been ordered. (The VB.NET version of this code would be very similar.) For this listing, you can assume that the .aspx markup file includes the nec- essary onCheckChangedand onClickclauses to call the event handler methods in the code-behind file. For example, the markup for the check boxes look like this:
<asp:checkbox id=”chkPepperoni” runat=”server” oncheckedchanged=”chkPepperoni_CheckedChanged” text=”Pepperoni” />
<asp:checkbox id=”chkMushrooms” runat=”server” oncheckedchanged=”chkMushrooms_CheckedChanged” text=”Mushrooms” />
<asp:checkbox id=”chkAnchovies” runat=”server” oncheckedchanged=”chkAnchovies_CheckedChanged” text=”Anchovies” />
Using CheckBox Controls
110
And the markup for the btnOrderPizzabutton looks like this:
<asp:button id=”btnOrderPizza” runat=”server” onclick=”btnOrderPizza_Click” text=”Button” />
Listing 1-1: The code-behind file for a pizza order page (C#)
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
public partial class Pizza2 : System.Web.UI.Page {
boolean boolPepperoni = false; boolean boolMushrooms = false; boolean boolAnchovies = false;
protected void chkPepperoni_CheckedChanged( object sender, EventArgs e)
{
boolPepperoni = chkPepperoni.Checked; }
protected void chkMushrooms_CheckedChanged( object sender, EventArgs e)
{
boolMushrooms = chkMushrooms.Checked; }
protected void chkAnchovies_CheckedChanged( object sender, EventArgs e)
{
boolAnchovies = chkAnchovies.Checked; }
protected void btnOrderPizza_Click(object sender, EventArgs e) { String order = “”; if (boolPepperoni) order += “Pepperoni<br>”; if (boolMushrooms) order += “Mushrooms<br>”; if (boolAnchovies) order += “Anchovies<br>”; lblOrder.Text = order; } }
Book II Chapter 1 Using Basic W eb Ser ver Controls
Using RadioButton Controls
111
Using RadioButton Controls
Radio buttons are similar to check boxes, but with a crucial difference: Radio buttons travel in groups, and a user can select only one radio button in each group at a time. When you click a radio button to select it, whatever radio button in the group was previously selected is automatically deselected. Figure 1-6 shows a page with two groups of radio buttons. The first group lets the user select the size of a pizza to be ordered. The second group lets the user select the crust style.
The markup used to create these radio buttons is as follows:
<asp:RadioButton ID=”rdoSizeMedium” runat=”server” GroupName=”Size” Text=”Medium” />
<asp:RadioButton ID=”rdoSizeLarge” runat=”server” GroupName=”Size” Text=”Large” />
<asp:RadioButton ID=”rdoSizeHumongous” runat=”server” GroupName=”Size” Text=”Humongous” />
<asp:RadioButton ID=”rdoCrustThin” runat=”server” GroupName=”Crust” Text=”Thin” />
<asp:RadioButton ID=”rdoCrustThick” runat=”server” GroupName=”Crust” Text=”Thick” />
As you can see, the GroupNameattribute specifies the group to which each radio button belongs. The first three buttons specify Sizeas the GroupName, while the last two specify Crust.
Figure 1-6:
A page with two groups of radio buttons.
Using Image Controls
112
As with check boxes, you use the Checkedproperty to determine whether a radio button has been selected. For example, here’s a snippet of C# code that sets a label’s Textproperty to indicate the size and crust style of a pizza:
string pizza = “”; if (rdoSizeMedium.Checked) pizza += “Medium “; else if (rdoSizeLarge.Checked) pizza += “Large “; else if (rdoSizeHumongous.Checked) pizza += “Humongous “; if (rdoCrustThin.Checked) pizza += “Thin Crust”; else if (rdoCrustThick.Checked)
pizza += “Thick Crust”; lblPizza.Text = pizza;
Here’s the equivalent in VB.NET:
Dim pizza As String = “” If rdoSizeMedium.Checked Then
pizza &= “Medium “ Else If rdoSizeLarge.Checked
pizza &= “Large “
Else If rdoSizeHumongous.Checked pizza &= “Humongous “
End If
If rdoCrustThin.Checked Then pizza &= “Thin Crust” Else If rdoCrustThick.Checked
pizza &= “Thick Crust” End If
lblPizza.Text = pizza