HTML Server Controls

   

Now that we've laid that ground work, you can begin to look at the specific HTML server controls. As I've said before, they are going to look very familiar because they are basically ASP.NET versions of existing HTML tags. Let's look at the HTML server controls.

HtmlAnchor

The HtmlAnchor is based off the HTML <a> tag and has the properties listed in Table 6.4 in addition to the HtmlContainerControl.

Table 6.4. HtmlAnchor Object Properties

Property

Description

Href

Gets or sets the URL to which the encapsulated item will link.

Name

Gets or sets the Name of the anchor element.

Target

Gets or sets the target frame or window in which the link will load. As with the HTML <a> tag, this is _self by default.

Title

Gets or sets the tooltip attribute of the <a> tag that is shown when you mouse over a text link.

The HtmlAnchor also raises the OnServerClick event, so you can use this server control to trigger subs and functions with this event. Take a look at some of these properties and this event in action. Notice in the following code that for the HtmlAnchor OnServerClick event to work, there must be a form tag with a runat="server" attribute surrounding the anchor.

Visual Basic .NET html_anchor_vb.aspx
<%@ page language="vb" runat="server"%>  <script  runat=server>  Sub Page_Load()      OurAnchor1.InnerText = "This will open a new window"      OurAnchor2.InnerText = "This will link back to this page and run a function"      OurAnchor1.Href = "newpage.htm"      OurAnchor1.Target = "_blank"  End Sub  Sub SetLabelText(sender As Object, e As System.EventArgs)      OurLabel.Text = "You have clicked and triggered the OnServerClick event"    End Sub  </script>  <html>  <head>  <title>HtmlControl Anchor</title>  </head>  <body>  <form runat="server">  <a  runat="server"/>  <br>  <a  onserverclick="SetLabelText" runat="server"/>  <br>  <ASP:Label  runat="server"/>  </form>  </body>  </html> 
C# html_anchor_cs.aspx
<%@ page language="cs" runat="server"%>  <script  runat=server>  void Page_Load(){     OurAnchor1.InnerText = "This will open a new window";      OurAnchor2.InnerText = "This will link back to this page and run a function";      OurAnchor1.HRef = "newpage.htm";      OurAnchor1.Target = "_blank";  }  void SetLabelText(object o, System.EventArgs s){     OurLabel.Text = "You have clicked and triggered the OnServerClick event";  }  </script>  <html>  <head>  <title>HtmlControl Anchor</title>  </head>  <body>  <form runat="server">  <a  runat="server"/>  <br>  <a  onserverclick="SetLabelText" runat="server"/>  <br>  <ASP:Label  runat="server"/>  </form>  </body>  </html> 
Resulting HTML
<a href="/ch6/newpage.htm"  target="_blank">This will open a new window</ graphics/ccc.gifa>  <a  href="javascript:__doPostBack('OurAnchor2','')">This will link back to  graphics/ccc.gifthis page and run a function</a> 

Notice in the resulting HTML that OurAnchor1 has a target and href attribute as set in the Page_Load event. Because my browser is JavaScript-enabled, ASP.NET uses a JavaScript function to perform the OnServerClick event.

Figure 6.3. You can set attributes and raise events in <a> tags using the HtmlAnchor control.
graphics/06fig03.gif

HtmlButton

The HtmlButton class is based on the <button> tag. Take caution when you are using this HTML control. It is fully supported in Internet Explorer version 4 and later, but isn't supported in Netscape Navigator 4.x at all. Netscape Navigator 6 supports this tag, but I can't say I'm completely thrilled at its implementation. The only time we use button tags at our firm is when we know we are in a controlled environment in which Internet Explorer is being used.

This is a container tag that can hold HTML, such as <img> tags and the like. In the following example, I have created two buttons one good and one naughty. These buttons have all the physical attributes of an <input> type form button except they can contain HTML.

The HtmlButton control also has an OnServerClick event that is used on both buttons in the following example. Notice that I set the content of the buttons and the styles of the two buttons in different ways. The "good" button has an image set as its InnerHtml property, whereas text is explicitly inserted between the opening and closing tags on the "naughty" button.

I also set the styles through the StyleCollection on the "good" button, but explicitly set the styles directly in the tag of the "naughty" button.

Visual Basic .NET html_button_vb.aspx
<%@ page language="vb" runat="server"%>  <script  runat=server>  Sub Page_Load()      OurButton.InnerHtml = "<img src="/books/1/582/1/html/2/"images/our_button.gif"">"      OurButton.Style("background-color")="#DDDDDD"      OurButton.Style("border-color")="#000000"      OurButton.Style("width")="150"      OurButton.Style("height")="35"  End Sub  Sub SetLabelText(sender As Object, e As System.EventArgs)      OurLabel.Text = "You have clicked the correct button. Very good"  End Sub  Sub SetLabelText2(sender As Object, e As System.EventArgs)      OurLabel.Text = "You just couldn't resist, could you.<br> Now I've got to take the  graphics/ccc.gifbad button away.<br><b>Click the one that is left, will ya?</b>"      OurButton2.visible=false  End Sub  </script>  <html>  <head>  <title>HtmlControl Button</title>  </head>  <body>  <form runat="server">  <button  onServerClick="SetLabelText" runat="server"/>&nbsp;  <button  onServerClick="SetLabelText2" style="background-color:#DDDDDD; graphics/ccc.gifborder-color:#000000;width:150;height:35" runat="server">Don't click this button</button>  <br><br>  <ASP:Label  runat="server"/>  </form>  </body>  </html> 
C# html_button_cs.aspx
<%@ page language="cs" runat="server"%>  <script  runat=server>  void Page_Load(){     OurButton.InnerHtml = "<img src=images/our_button.gif>";      OurButton.Style["background-color"]="#DDDDDD";      OurButton.Style["border-color"]="#000000";      OurButton.Style["width"]="150";      OurButton.Style["height"]="35";  }  void SetLabelText(object o, System.EventArgs e){     OurLabel.Text = "You have clicked the correct button. Very good";  }  void SetLabelText2(object o, System.EventArgs e){     OurLabel.Text = "You just couldn't resist, could you.<br> Now I've      got to take the bad button away.<br><b>Click the one that is left,      will ya?</b>";      OurButton2.Visible=false;  }  </script>  <html>  <head>  <title>HtmlControl Button</title>  </head>  <body>  <form runat="server">  <button  onServerClick="SetLabelText" runat="server"/>&nbsp;  <button  onServerClick="SetLabelText2" style="background-color:#DDDDDD; graphics/ccc.gifborder-color:#000000;width:150;height:35" runat="server">Don't click this button</button>  <br><br>  <ASP:Label  runat="server"/>  </form>  </body>  </html> 
Resulting HTML
<button language="javascript" onclick="__doPostBack('OurButton','')"   graphics/ccc.gifstyle="background-color:#DDDDDD;border-color:#000000;width:150;height:35;"><img  graphics/ccc.gifsrc="/books/1/582/1/html/2/images/our_button.gif"></button>  <button language="javascript" onclick="__doPostBack('OurButton2','')"   graphics/ccc.gifstyle="background-color:#DDDDDD;border-color:#000000;width:150;height:35">Don't click is  graphics/ccc.gifbutton</button> 

Notice in Figure 6.4 that there are two buttons, as expected. The first contains an image as its HTML between the opening and closing <button> tags, whereas the other button contains just text.

Figure 6.4. These are the rendered buttons on the page's first load. Notice that the button on the left contains an image as its content.
graphics/06fig04.gif

Also notice in Figure 6.5 that after clicking the "naughty" button we trigger the SetLabelText2 function with the OnServerClick event and set this button's Visible property to false. When the page is returned to the browser, the "naughty" button is gone and you get a tongue lashing.

Figure 6.5. The button page after clicking the "Naughty" button and executing the SetLabelText2 function. You get scolded and hide the "Naughty" button.
graphics/06fig05.gif

HtmlForm

The HtmlForm class is the core of ASP.NET (see Table 6.5). It is what makes all the funky event-driven stuff we've been seeing like OnServerclick. The HtmlForm object is not a whole lot different from a standard HTML form, with two exceptions. First…you guessed it, runat="server"; and second, there is no accessible action attribute. An HtmlForm MUST post back to itself. This is at the root of ASP.NET web forms and their entrenched nature of using PostBack as a programming paradigm. Trust me it is a good choice and the fact that you can't post your pages to other pages makes many other things such as server events and advanced form validation possible.

Table 6.5. HtmlForm Object Properties

Property

Description

EncType

This property instructs the browser on what encoding type to use when posting form data to the server. By default this is application/ x-www-form-urlencoded, but if you are using an HtmlInputFile object for browsing and uploading files, you will need to change this property to multipart/form-data.

Method

This instructs the browser in what collection to send the form data. The Post() method places the form data in the form collection in the HTTP headers and can contain file attachments (such as files you want to upload). The Get() method places the form data in the QueryString (URL) collection, cannot have attachments, and is limited to 4Kb of data.

Name

This sets the name attribute of the <form> tag.

Target

Gets or sets the target frame or window to which the form will be posted. As with the HTML <form> tag, this is _self by default.

HtmlGenericControl

The HtmlGenericControl is available for providing properties and methods for HTML tags that the .NET Framework doesn't address with a specific object class. Examples of this would be the <body>, <span>, and <div>. None of these tags have their own dedicated HTML server control.

This object has a single exception to the other HTML server controls in that its TagName property is Read/Write instead of Readonly. Of course, if you think about this a little it makes sense, because you need to set the tag's Tagname to whatever generic element you want to runat="server".

You can set any available property or method available to the HtmlContainerControl to any HtmlGenericControl. In the following examples I am reiterating some things we've already covered with regard to setting properties and using methods to reinforce their use with the HtmlGenericControl.

Visual Basic .NET html_generic_vb.aspx
<%@ page language="vb" runat="server"%>  <script  runat=server>  Sub Page_Load()      OurBody.Attributes("bgcolor")="#CCCCCC"      OurDiv.InnerHtml = "This text will be <b>Centered</b>"      OurDiv.Attributes.Add("align","center")      OurSpan.InnerText = "This is our span"      OurSpan.Style("font-family")="arial,helvetica,sanserif"  End Sub  </script>  <html>  <head>  <title>HtmlControl Generic</title>  </head>  <body  runat="server">  <div  runat="server"/>  <span  runat="server"/>  </body>  </html> 
C# html_generic_cs.aspx
<%@ page language="cs" runat="server"%>  <script  runat=server>  void Page_Load(){     OurBody.Attributes["bgcolor"]="#CCCCCC";      OurDiv.InnerHtml = "This text will be <b>Centered</b>";      OurDiv.Attributes.Add("align","center");      OurSpan.InnerText = "This is our span";      OurSpan.Style["font-family"]="arial,helvetica,sanserif";  }  </script>  <html>  <head>  <title>HtmlControl Button</title>  </head>  <body  runat="server">  <div  runat="server"/>  <span  runat="server"/>  </body>  </html> 

As you can see in Figure 6.6, the <body> tag's bgcolor attribute was set to #CCCCCC, the <div> tag's align attribute was added through the AttributeCollection's Add method and set to align="center", and the <span> tag's font-family style was set to us sanserif fonts. This was all done by affecting these HtmlGenericControls programmatically during the Page_Load event.

Figure 6.6. The HtmlGenericControl allows you to manipulate properties and methods of HTML tags that don't have explicit corresponding HTML server controls.
graphics/06fig06.gif

HtmlImage

The HtmlImage control, as you probably have guessed, is associated with the <img> tag in HTML. Table 6.6 describes the properties associated with the HtmlImage control.

Table 6.6. HtmlImage Object Properties

Property

Description

Align

Gets or sets the align property of the image object. This property affects where an image is rendered in relation to its surrounding content.

Alt

Gets or sets the text that displays when an image is moused over or delivered to voice HTML readers.

Border

Gets or sets the border width of a image in pixels.

Height

Gets or sets the height of the image in pixels.

Src

Gets or sets the path and image name that is the source of the image.

Width

Gets or sets the width of the image in pixels.

Let's take a look at manipulating the properties of the HtmlImage control.

Visual Basic .NET html_image_vb.aspx
<%@ page language="vb" runat="server"%>  <script  runat=server>  Sub Page_Load()      ProductImage.Src = "images/brown_jeans.jpg"      ProductImage.Width = 176      ProductImage.Height = 320      ProductImage.Border = 1  End Sub  Sub ShowBrownJeans(sender As Object, e As System.EventArgs)      ProductImage.Src = "images/brown_jeans.jpg"  End Sub  Sub ShowBlueJeans(sender As Object, e As System.EventArgs)      ProductImage.Src = "images/blue_jeans.jpg"  End Sub  </script>  <html>  <head>  <title>HtmlControl Generic</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <table width="500" border="0" cellspacing="0" cellpadding="2">  <tr bgcolor="#999999">  <td colspan="2">Peter's Denim Emporium</td>  </tr>  <tr>  <td width="150" bgcolor="#CCCCCC">&nbsp;</td>  <td width="350">Product: Peter Jeans</td>    </tr>  <tr>  <td width="150" valign="top" align="center" bgcolor="#CCCCCC">  <u>Available Colors</u><br>  <a OnServerClick="ShowBrownJeans" runat="server">Brown</a><br>  <a OnServerClick="ShowBlueJeans" runat="server">Blue</a>  </td>  <td width="350" align="center">  <img  runat="server"/>  </td>  </tr>  </table>  </form>  </body>  </html> 
C# html_image_cs.aspx
<%@ page language="cs" runat="server"%>  <script  runat=server>  void Page_Load(){     ProductImage.Src = "images/brown_jeans.jpg";      ProductImage.Width = 176;      ProductImage.Height = 320;      ProductImage.Border = 1;  }  void ShowBrownJeans(object o, System.EventArgs s){     ProductImage.Src = "images/brown_jeans.jpg";  }  void ShowBlueJeans(object o, System.EventArgs s){     ProductImage.Src = "images/blue_jeans.jpg";  }  </script>  <html>  <head>  <title>HtmlControl Generic</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <table width="500" border="0" cellspacing="0" cellpadding="2">  <tr bgcolor="#999999">  <td colspan="2">Peter's Denim Emporium</td>  </tr>  <tr>  <td width="150" bgcolor="#CCCCCC">&nbsp;</td>  <td width="350">Product: Peter Jeans</td>  </tr>  <tr>  <td width="150" valign="top" align="center" bgcolor="#CCCCCC">  <u>Available Colors</u><br>  <a OnServerClick="ShowBrownJeans" runat="server">Brown</a><br>  <a OnServerClick="ShowBlueJeans" runat="server">Blue</a>  </td>  <td width="350" align="center">  <img  runat="server"/>  </td>  </tr>  </table>  </form>  </body>  </html> 

You can see the result of this example in Figure 6.7. On Page_Load many of the properties of the HtmlImage object are set, but visitors are given the ability to see different colors of jeans based on their selections, and through functions the Src property of the HtmlImage object on the page is changed.

Figure 6.7. You can programmatically manipulate an HtmlImage object's properties.
graphics/06fig07.gif

HtmlInputButton

The HtmlInputButton object supports three different types of HTML input elements: Button, Submit, and Reset. These are parallel to their HTML counterparts and have all the same properties with the exception of one additional one.

The additional property is called CauseValidation, a Boolean value that is true by default. You would utilize this property only if you wanted to set it to false and override the processing of any validation you may be performing in your HtmlForm.

The HtmlInputButton can use the OnServerClick event for all three types. Take a look at some examples.

Visual Basic .NET html_inputbutton_vb.aspx
<%@ page language="vb" runat="server"%>  <script  runat=server>  dim TextBox1Text as string  = "Insert your First Name"  dim TextBox2Text as string  = "Insert your Last Name"  Sub Page_Load()      if (Page.IsPostBack)then          OurSpan.InnerText = "Your Name is " + TextBox1.Value + " " + TextBox2.Value      else          TextBox1.Value = TextBox1Text          TextBox2.Value = TextBox2Text      end if  End Sub  Sub ReInitPage(sender As Object, e As System.EventArgs)          TextBox1.Value = TextBox1Text          TextBox2.Value = TextBox2Text          OurSpan.InnerText = ""  End Sub  </script>  <html>  <head>  <title>HtmlControl Generic</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <input type="text"  runat="server"><br>  <input type="text"  runat="server"><br>  <input type="submit"  value="Submit Form" runat="server">  <input type="reset"  value="Reset Values" runat="server"><br>  <input type="button"  OnServerClick="ReInitPage"  value="Set Page to  graphics/ccc.gifOriginal Settings" runat="server">  <br><br>  <span  runat="server"/>  </form>  </body>  </html> 
C# html_inputbutton_cs.aspx
<%@ page language="cs" runat="server"%>  <script  runat=server>  string TextBox1Text = "Insert your First Name";  string TextBox2Text = "Insert your Last Name";  void Page_Load(){     if (Page.IsPostBack){         OurSpan.InnerText = "Your Name is " + TextBox1.Value + " " + TextBox2.Value;      }else{         TextBox1.Value = TextBox1Text;          TextBox2.Value = TextBox2Text;      }  }  void ReInitPage(object o, System.EventArgs s){          TextBox1.Value = TextBox1Text;          TextBox2.Value = TextBox2Text;          OurSpan.InnerText = "";  }  </script>  <html>  <head>  <title>HtmlControl Generic</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <input type="text"  runat="server"><br>  <input type="text"  runat="server"><br>  <input type="submit"  value="Submit Form" runat="server">  <input type="reset"  value="Reset Values" runat="server"><br>  <input type="button"  OnServerClick="ReInitPage" value="Set Page to  graphics/ccc.gifOriginal Settings" runat="server">  <br><br>  <span  runat="server"/>  </form>  </body>  </html> 

You can see the result of this example in Figure 6.8, where the three types of HtmlInputButton objects are rendered. The Submit type does a standard form submit, which will cause the Page object's IsPostBack property to be true and so that that branch will execute. The Reset type sets the form back to its original state when it was rendered to the browser. In this particular instance, this will either be the values set by the global variables, or TextBox1Text and TextBox2Text the first time the page has loaded, or whatever value you posted from the previous page.

Figure 6.8. HtmlInputButton objects can handle many different types of functions.
graphics/06fig08.gif

The Button type does whatever you tell it to through the OnServerClick event; in this case it sets the text boxes back to the value of the global variables and set the span's InnerText value to nothing. The Button type is similar to the HtmlButton in function. It is fortunately cross-browser-compatible, but unfortunately doesn't contain an InnerHtml property, so inserting images and other HTML elements isn't possible.

HtmlInputCheckBox

The HtmlInputCheckBox allows you to access and manipulate the property's <input type="checkbox">. This HTML server control has a property called Checked that you may Get or Set, and uses a different server event that you haven't seen yet, called OnServerChange.

OnServerChange can recognize whether the state of a check box has changed between posts. This doesn't submit the form or trigger the event immediately, but it lies in wait for the form to be posted by another means; then the event is fired.

Visual Basic .NET html_inputcheckbox_vb.aspx
<%@ page language="vb" runat="server"%>  <script  runat=server>  Sub InspectCheckBoxes(sender As Object, e As System.EventArgs)      if CheckBox1.Checked = true then          if CheckBox2.Checked = true then              OurSpan.InnerText = "Both CheckBoxes are Checked"          else              OurSpan.InnerText = "Just CheckBox 1 is Checked"          end if      elseif CheckBox2.Checked = true then              OurSpan.InnerText = "Just CheckBox 2 is Checked"      else              OurSpan.InnerText = "No CheckBoxes are Checked"      end if  End Sub  Sub CheckBoxChanged(sender As Object, e As System.EventArgs)      OurSpan2.InnerText = "You changed one of the CheckBoxes between      submits"  End Sub  </script>  <html>  <head>  <title>HtmlControl InputCheckbox</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  CheckBox 1  <input type="checkbox"  OnServerChange="CheckBoxChanged" runat="server"> graphics/ccc.gif<br>  CheckBox 2  <input type="checkbox"  OnServerChange="CheckBoxChanged" runat="server"> graphics/ccc.gif<br>  <input type="submit"  OnServerClick="InspectCheckBoxes" runat="server">  <br><br>  <span  runat="server"/><br>  <span  enableviewstate="false" runat="server"/>  </form>  </body>  </html> 
C# html_inputcheckbox_cs.aspx
<%@ page language="cs" runat="server"%>  <script  runat=server>  void InspectCheckBoxes(object o, System.EventArgs s){     if (CheckBox1.Checked == true){         if(CheckBox2.Checked == true){             OurSpan.InnerText = "Both CheckBoxes are Checked";          }else{             OurSpan.InnerText = "Just CheckBox 1 is Checked";          }      }else if (CheckBox2.Checked == true){             OurSpan.InnerText = "Just CheckBox 2 is Checked";      }else{             OurSpan.InnerText = "No CheckBoxes are Checked";      }  }  void CheckBoxChanged(object o, System.EventArgs s){     OurSpan2.InnerText = "You changed one of the CheckBoxes between      submits";  }  </script>  <html>  <head>  <title>HtmlControl InputCheckbox</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  CheckBox 1  <input type="checkbox"  OnServerChange="CheckBoxChanged" runat="server"> graphics/ccc.gif<br>  CheckBox 2  <input type="checkbox"  OnServerChange="CheckBoxChanged" runat="server"> graphics/ccc.gif<br>  <input type="submit"  OnServerClick="InspectCheckBoxes" runat="server">  <br><br>  <span  runat="server"/><br>  <span  enableviewstate="false" runat="server"/>  </form>  </body>  </html> 

You can see the results of the preceding code in Figure 6.9.

Figure 6.9. The HtmlInputCheck Box has a checked property and an OnServerChange event at its disposal.
graphics/06fig09.gif

HtmlInputFile

Yahoooeeee!!!!! This is another huge improvement in ASP.NET. Before, with traditional ASP, when you needed to provide a way for someone to upload a file, you generally needed to use a third-party component to provide the functionality, although there were a few other more complicated ways to do it without one. But these weren't always available, either, depending on what your hosting situation was and whether you were allowed to install components on your web server.

The .NET Framework has made a way. Can I hear a hallelujah? How about an amen? No matter what your religious beliefs you should shout out a big thank you because this is a REALLY AWESOME THING!!! The HtmlInputFile control has all you need to cure your uploading ills. It's got the properties. It's got the methods. It's got all that and more. Check out Table 6.7 for a look-see.

Table 6.7. HtmlInputFile Object Properties

Property

Description

Accept

Gets or sets the MIME encodings that can be used in the HtmlInputFile control.

MaxLength

Gets or sets the maximum length of the path statement for the file selected for upload.

PostFile

This is the magic property. It's really an instance of another class that is called HttpPostedFile, located in System.Web namespace.

Size

Gets or sets the size of the file textbox in the browser.

The Accept, MaxLength, and Size properties don't need to be addressed, but let's dig in a bit to the PostFile property. Like it says in the table, this is an instance of the HttpPostedFile class located in the System.Web namespace. It has three properties you can see in Table 6.8, and one magic method.

Table 6.8. HttpPostedFile Object Properties

Property

Description

ContentLength

Gets the size in bytes of an uploaded file.

ContentType

Gets the MIME content type of a uploaded file.

FileName

Gets the full path and filename for the upload file on the client's machine (example: c:\mydocuments\file.jpg).

The magical method is the SaveAs method. This saves an uploaded file to the server and bypasses the need for third-party components. The next code block demonstrates these properties and methods. I use the ContentType property to check and allow only JPEG images to be uploaded. I also use the ContentLength property to restrict the file size to allow only files that are under 20Kb to be uploaded.

Another thing to notice, and something you may remember from the HtmlForm section of this chapter, is that the form must contain the enctype= "multipart/form-data"; otherwise, it won't work.

Look for comments in the UploadFile function that will explain what stuff is going on and when. This may seem a bit complicated, but just follow the comments (Visual Basic .NET comment line starts with a single quote (') and a C# comment line starts with two forward slashes(//)).

Visual Basic .NET html_inputfile_vb.aspx
<%@ Import Namespace="System.IO" %>  <script language="VB" runat="server">  Sub UploadFile(sender As Object, e As EventArgs)      dim TheFile as String = FileBox.PostedFile.FileName      If TheFile.Length > 0 Then          dim FileType as String = FileBox.PostedFile.ContentType          dim FileSize as Integer = FileBox.PostedFile.ContentLength          'Check to see if the file is a JPEG          if  FileType <> "image/jpeg" AND FileType <> "image/pjpeg" then              OurSpan.InnerHtml = "You can <b>Only Upload Jpegs.</b> Got It?"          'Check to see if file is larger than 20k          elseif FileSize > 20000 then              OurSpan.InnerHtml = "You can't upload a file bigger than              20k. Yours was bigger."          'if we pass both tests,proceed to try to upload file          else                    'Build file path              dim filepath as String = Mappath("") + "\uploadedfiles\"                    dim filename as String = TheFile.SubString (TheFile.LastIndexOf("\")+1)                    dim fullpath = filepath + filename                    'Try to upload file              Try                        FileBox.PostedFile.SaveAs(fullpath)                       OurSpan.InnerHtml = "A file named <b>" + filename + "</b> was  graphics/ccc.gifuploaded successfully<br>"                       OurSpan.InnerHtml += "It was uploaded to the <b>" + filepath + "</b>  graphics/ccc.gifdirectory"                    Catch Exc As Exception                       OurSpan.InnerHtml = "Error saving file <b>" & filename & "</b><br>"  graphics/ccc.gif& Exc.ToString                    End Try                end if      Else              OurSpan.InnerText = "Please specify a file to upload"      End If  End Sub  </script>  <html>  <head>  <title>Html InputFile</title>  </head>  <body>  <form enctype="multipart/form-data" runat="server">  Upload a JPEG Image under 20k<br>  <input  type="file" runat="server"><br>  <input type=button  value="Upload" OnServerClick="UploadFile"  graphics/ccc.gifrunat="server">    <br><span  runat="server" />  </form>  </body>  </html> 
C# html_inputfile_cs.aspx
<%@ Import Namespace="System.IO" %>  <script language="VB" runat="server">  Sub UploadFile(sender As Object, e As EventArgs)      dim TheFile as String = FileBox.PostedFile.FileName      If TheFile.Length > 0 Then          dim FileType as String = FileBox.PostedFile.ContentType          dim FileSize as Integer = FileBox.PostedFile.ContentLength          //Check to see if the file is a JPEG          if  FileType <> "image/jpeg" AND FileType <> "image/pjpeg" then              OurSpan.InnerHtml = "You can <b>Only Upload Jpegs.</b> Got It?"          //Check to see if file is larger than 20k          elseif FileSize > 20000 then              OurSpan.InnerHtml = "You can't upload a file bigger than 20k. Yours was  graphics/ccc.gifbigger."          //if we pass both tests,proceed to try to upload file          else                    //Build file path              dim filepath as String = Mappath("") + "\uploadedfiles\"                    dim filename as String = TheFile.SubString (TheFile.LastIndexOf("\")+1)                    dim fullpath = filepath + filename                    //Try to upload file              Try                        FileBox.PostedFile.SaveAs(fullpath)                       OurSpan.InnerHtml = "A file named <b>" + filename + "</b> was  graphics/ccc.gifuploaded successfully<br>"                       OurSpan.InnerHtml += "It was uploaded to the <b>" + filepath + "</b>  graphics/ccc.gifdirectory"                    Catch Exc As Exception                       OurSpan.InnerHtml = "Error saving file <b>" & filename & "</b><br>"  graphics/ccc.gif& Exc.ToString                    End Try                end if      Else              OurSpan.InnerText = "Please specify a file to upload"      End If  End Sub  </script>  <html>  <head>  <title>Html InputFile</title>  </head>  <body>  <form enctype="multipart/form-data" runat="server">  Upload a JPEG Image under 20k<br>  <input  type="file" runat="server"><br>  <input type=button  value="Upload" OnServerClick="UploadFile"  graphics/ccc.gifrunat="server">  <br><span  runat="server" />  </form>  </body>  </html> 

In Figure 6.10 you can see the results of a successful JPEG file being uploaded to the server.

Figure 6.10. The .NET Framework supplies a way for you to upload files to a server without using any third-party components.
graphics/06fig10.gif

HtmlInputHidden

An HtmlInputHidden object allows access to properties of the <input type= "hidden"> object. This element is an intricate part of how ASP.NET maintains information from page to page and also how ASP.NET pages pass server event variables back to the server in a JavaScript enabled browser.

In the past, with traditional ASP, hidden form boxes were one way of persisting data from page to page. This needed to be done manually by the programmer. Now, thankfully, ASP.NET does this for you with ViewState and the use of hidden form boxes.

There still may be practical uses for this control in instances where you wish to pass data back to the server without it being visible or editable by the user.

The HtmlInputHidden control has no properties or methods of its own and simply inherits them from the HtmlInputControl.

A simple example of the code necessary for this control, which is applicable in both languages, looks like the following:

 <input type="hidden" runat="server"> 

HtmlInputImage

The HtmlInputImage object is kinda like the best of all worlds to me when it comes to things that act like buttons. The HtmlButton object lets you insert an image into its content, but it isn't cross-browser compatible. The HtmlInputButton is kinda kludgy and homely without some cascading style sheet intervention. The HtmlInputImage object has all the function of an <input type="submit">, except that the image is visibly offset when you click it, and the great advantage of being able to use an image in the first place is so that your Submit buttons can look the way you'd like.

The HtmlInputImage object actually has all the same properties and methods that an HtmlImage has, with two nifty advantages. First, as I said, it submits the form in which it is contained, and second, it sends X,Y coordinates of the position where the image was clicked. This can be quite handy for a number of different situations in which knowing where a user clicked on an image might be helpful, such as a map. Notice that I use the ImageClickEventArgs from the System.Web.UI namespace in place of the standard EventArgs. This gives me access to the X,Y coordinates that are properties of this class.

Visual Basic .NET html_inputimage_vb.aspx
<%@ page language="vb" runat="server"%>  <script  runat=server>  Sub PickDessert(o as object , e as ImageClickEventArgs)      OurSpan.InnerText = "You picked "       if e.X < 135 then           if e.Y < 125 then               OurSpan.InnerText += "Pumpkin Pie"           else               OurSpan.InnerText += "Ice Cream Sundae"           end if       else           if e.Y < 125 then               OurSpan.InnerText += "Cheesecake"           else               OurSpan.InnerText += "Cookies, These are my favorite too!"           end if       end if  end Sub  </script>  <html>  <head>  <title>HtmlControl InputImage</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <div align="center">  <h2>What is your favorite dessert?</h2>  <input type="image"  OnServerClick="PickDessert" src="/books/1/582/1/html/2/images/ graphics/ccc.giffavorite_dessert.gif" runat="server">  <br><br>  <span  runat="server"/>  </div>  </form>  </body>  </html> 
C# html_inputimage_cs.aspx
<%@ page language="cs" runat="server"%>  <script  runat=server>  void PickDessert(object o, ImageClickEventArgs e){     OurSpan.InnerText = "You picked ";       if (e.X < 135){          if (e.Y < 125){              OurSpan.InnerText += "Pumpkin Pie";           }else{              OurSpan.InnerText += "Ice Cream Sundae";           }       }else{          if (e.Y < 125){              OurSpan.InnerText += "Cheesecake";           }else{              OurSpan.InnerText += "Cookies, These are my favorite too!";           }       }  }  </script>  <html>  <head>  <title>HtmlControl InputImage</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <div align="center">  <h2>What is your favorite dessert?</h2>  <input type="image"  OnServerClick="PickDessert" src="/books/1/582/1/html/2/images/ graphics/ccc.giffavorite_dessert.gif" runat="server">  <br><br>  <span  runat="server"/>  </div>  </form>  </body>  </html> 

You can see the results of these (and learn what my favorite dessert is, as well) in Figure 6.11.

Figure 6.11. HtmlInputImage gives you access to the X,Y coordinates of where a user clicked and acts like a form submit as well.
graphics/06fig11.gif

HtmlInputRadioButton

The HtmlInputRadioButton is the server control counterpart to the HTML radio button (as if you couldn't figure that out). As if it weren't totally obvious that every single HTML server control has a matching HTML tag, and as if you're not smart enough to figure that out. Heck. Maybe I don't even need to write the rest of this chapter. Maybe nobody will notice if I just jump to the next chapter and forget about the rest of the server controls.

Anywho, the HtmlInputRadioButton has three additional properties that need to be mentioned, which are described in Table 6.9.

Table 6.9. HtmlInputRadioButton Object Properties

Property

Description

Checked

Gets or sets whether a radio button is the selected one in its group.

Name

Allows you to group radio buttons.

Value

Gets or sets the value of a radio button.

This control also has the OnServerChange event available for use. Now look at this control in action.

Visual Basic .NET html_radiobutton_vb.aspx
<%@ page language="vb" runat="server"%>  <script  runat=server>  Sub InspectRadioButton(o as object, s as System.EventArgs)      OurSpan.InnerText = "You picked " + Request.Form("Dessert")      if Radio4.Checked then OurSpan.InnerText += ", That's my favorite too!"  End Sub  Sub CheckBoxChanged(o as object, s as System.EventArgs)      OurSpan2.InnerText = "You changed your selection this time"  End Sub  </script>  <html>  <head>  <title>HtmlControl InputRadioButton</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <h2>What is your favorite dessert?"</h2>  <input type="radio"  Name="Dessert" value="Pumpkin Pie"  graphics/ccc.gifOnServerChange="CheckBoxChanged" runat="server">  Pumpkin Pie<br>  <input type="radio"  Name="Dessert" value="Cheesecake"  graphics/ccc.gifOnServerChange="CheckBoxChanged" runat="server">  Cheesecake<br>  <input type="radio"  Name="Dessert" value="Ice Cream"  graphics/ccc.gifOnServerChange="CheckBoxChanged" runat="server">  Ice Cream<br>  <input type="radio"  Name="Dessert" value="Cookies"  graphics/ccc.gifOnServerChange="CheckBoxChanged" runat="server">  Cookies<br><br>  <input type="submit"  OnServerClick="InspectRadioButton" runat="server">  <br><br>  <span  runat="server"/><br>  <span  enableviewstate="false" runat="server"/>  </form>  </body>  </html> 
C# html_radiobutton_cs.aspx
<%@ page language="cs" runat="server"%>  <script  runat=server>  void InspectRadioButton(object o, System.EventArgs s){     OurSpan.InnerText = "You picked " + Request.Form["Dessert"];      if (Radio4.Checked)          OurSpan.InnerText += ", That's my favorite too!";  }  void CheckBoxChanged(object o, System.EventArgs s){     OurSpan2.InnerText = "You changed your selection this time";  }  </script>  <html>  <head>  <title>HtmlControl InputRadioButton</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <h2>What is your favorite dessert?"</h2>  <input type="radio"  Name="Dessert" value="Pumpkin Pie"  graphics/ccc.gifOnServerChange="CheckBoxChanged" runat="server">  Pumpkin Pie<br>  <input type="radio"  Name="Dessert" value="Cheesecake"  graphics/ccc.gifOnServerChange="CheckBoxChanged" runat="server">  Cheesecake<br>  <input type="radio"  Name="Dessert" value="Ice Cream"  graphics/ccc.gifOnServerChange="CheckBoxChanged" runat="server">  Ice Cream<br>  <input type="radio"  Name="Dessert" value="Cookies"  graphics/ccc.gifOnServerChange="CheckBoxChanged" runat="server">  Cookies<br><br>  <input type="submit"  OnServerClick="InspectRadioButton" runat="server">  <br><br>  <span  runat="server"/><br>  <span  enableviewstate="false" runat="server"/>  </form>  </body>  </html> 

You can see the results of this code in Figure 6.11. Notice in the code that I used Request.Form to retrieve the value of which radio button was checked. This is a time when programmatically finding out what a user selected is a bit more work than reverting to using Request.Form. If I wanted to figure out which one of the group was picked by the user by inspecting the Checked property, I'd have to write a loop for each control in the group. In this way I get the value with a simple request.

It is important to note that the Name property of the HtmlInputRadioButton must be the same for all HtmlInputRadioButtons that you'd like to group together.

I still use the checked property to see whether the user picked my favorite dessert, so both the more traditional way and the ASP.NET object way are useful and valid here.

HtmlInputText

This server control takes care of both the <input type="text"> and <input type="password"> text box types. This server control has three additional properties available, described in Table 6.10.

Table 6.10. HtmlInputText Object Properties

Property

Description

MaxLength

Gets or sets the maximum allowable number of characters that a user can put in the text box or password box.

Size

Gets or sets how many characters wide the text box or password box is.

Value

Gets or sets the value of the text box or password box.

Both the text box and password box also make the OnServerChange event available for programmatic use.

Visual Basic .NET html_inputtext_vb.aspx
<%@ page language="vb" runat="server"%>  <script  runat=server>  Sub Page_Load()      if Page.IsPostBack then          if Password.Value.ToLower() = "cookies" then              OurSpan.InnerHtml = "<b>Hey " + Name.Value + ", You're In!!!"          else              if Password.Value <> Failed.Value then                  OurSpan.InnerHtml = "No dice " + Name.Value + ". Think, what's my  graphics/ccc.giffavorite dessert?"                  Failed.Value = Password.Value              else                  OurSpan.InnerHtml = "Yo" + Name.Value + ", Did you think the password  graphics/ccc.gifmagically changed from what you put in last time?"              end if          end if      end if  end sub  </script>  <html>  <head>  <title>HtmlControl TextBox</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <input type="text"  runat="server"> What's Your Name?<br>  <input type="password"  runat="server"> What's the Password? (hint:My  graphics/ccc.gifFavorite Dessert)<br>  <input type="submit"  value="Submit Form" runat="server">  <input type="hidden"  runat="server">  <br><br>  <span  runat="server"/>  </form>  </body>  </html> 
C# html_inputtext_cs.aspx
<%@ page language="cs" runat="server"%>  <script  runat=server>  void Page_Load(){     if (Page.IsPostBack){         if (Password.Value.ToLower() == "cookies"){             OurSpan.InnerHtml = "<b>Hey " + Name.Value + ", You're In!!!";          }else{             if(Password.Value != Failed.Value){                 OurSpan.InnerHtml = "No dice " + Name.Value + ". Think, what's my  graphics/ccc.giffavorite dessert?";                  Failed.Value = Password.Value;              }else{                 OurSpan.InnerHtml = "Yo" + Name.Value + ", Did you think the password  graphics/ccc.gifmagically changed from what you put in last time?";              }          }      }  }  </script>  <html>  <head>  <title>HtmlControl TextBox</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <input type="text"  runat="server"> What's Your Name?<br>  <input type="password"  runat="server"> What's the Password? (hint:My  graphics/ccc.gifFavorite Dessert)<br>  <input type="submit"  value="Submit Form" runat="server">  <input type="hidden"  runat="server">  <br><br>  <span  runat="server"/>  </form>  </body>  </html> 

The results for this example can be seen in Figure 6.12. Notice the HtmlInputHidden control on the page. Here is a situation where I want to maintain a value and pass it across page posts. If the user login fails I store the failing password in the box. Then on the user's next try, if he fails again, I check to see whether the newly submitted password is identical to the last failed password. If so, I give him a nasty message about not changing the password and submitting again.

Figure 6.12. The HtmlInputRadioButton provides a way to manipulate and control radio buttons in ASP.NET.
graphics/06fig12.gif
Figure 6.13. The HtmlInputText control handles both the standard text box and the password box.
graphics/06fig13.gif

HtmlSelect

The HtmlSelect object allows you to access and affect the properties and methods of the <select runat="server"> tag. This object has several additional properties and some inherited methods as well. Have a look in Table 6.11.

Table 6.11. HtmlSelect Object Properties

Property

Description

Datasource

Gets or sets the value of what is being used as a datasource for the HtmlSelect options.

DataTextField

Gets or sets the field in a table or hashtable that will populate the text portion of a HtmlSelect object's items.

DataValueField

Gets or sets the field in a table or hashtable that will populate the value portion of an HtmlSelect object's items.

Items

Gets or sets the option item's value.

Multiple

Gets or sets a Boolean value declaring whether a select box will allow the user to pick multiple values in the box.

SelectedIndex

Gets or sets the index value of the selected option. The index start at 0 and increments by 1 through the number of options.

Size

Gets or sets how many lines of the select box are displayed. If you select Multiple, it defaults to multiple lines. You can specify how many lines with this property.

Value

Gets or sets the value of the Select box.

The Items property, as with so many other things I've mentioned before, is an instance of another object and makes its properties and methods available. The Items property is an instance of ListItemCollection in the System.Web.UI.WebControls namespace. It has a boatload of properties and methods that will be useful for manipulating your HtmlSelect control, which are described in Table 6.12.

Table 6.12. ListItemCollection Object Properties

Property/Method

Description

Add (M)

Provides a way to add a new option to the HtmlSelect control.

Count (P)

Returns the number of Items in the HtmlSelect control.

Clear (M)

Empties the entire HtmlSelect control.

Insert (M)

Inserts an Item into the HtmlSelect control at the specified Index.

Remove (M)

Removes the specified Item from the HtmlSelect control at the specified Index.

Visual Basic .NET html_select_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  Sub Page_Load(sender As Object, e As EventArgs)      dim myArray() as String = {"Pumpkin Pie", "Cheesecake", "Ice Cream Sundae",  graphics/ccc.gif"Cookies"}      if not IsPostBack          Dessert.DataSource = myArray          Dessert.DataBind()      end if  end sub  Sub PickDessert(sender As Object, e As EventArgs)      OurSpan.InnerText = "You chose: " + Dessert.Value      if Dessert.Value = "Cookies" Then          OurSpan.InnerText += ". These are my favorite too."      end if  End Sub  Sub AddNewDessert(sender As Object, e As EventArgs)      if NewDessert.Value <> "" Then          Dessert.Items.Add(NewDessert.Value)      end if  End Sub  </script>  <html>  <head>  <title>HtmlControl Select</title>  </head>  <body>  <form runat=server>  Select a dessert:<br>  <select  runat="server" />  <input type="button" runat="server" Value="Submit" OnServerClick="PickDessert">  <br><br>  If you don't see <b>your</b> favorite dessert in the list, you can add it:<br>  <input type="text"  runat="server">  <input type="button" runat="server" Value="Add" OnServerClick="AddNewDessert">  <br><br>  <span  runat="server"></span>  </form>  </body>  </html> 
C# html_select_cs.aspx
<%@ page language="cs" runat="server"%>  <script runat=server>  void Page_Load(object sender, EventArgs e) {     string[] myArray = {"Pumpkin Pie", "Cheesecake", "Ice Cream Sundae", "Cookies"};      if (!IsPostBack) {         Dessert.DataSource = myArray;          Dessert.DataBind();      }  }  void PickDessert(object sender, EventArgs e) {     OurSpan.InnerText = "You chose: " + Dessert.Value;      if (Dessert.Value == "Cookies") {         OurSpan.InnerText += ". These are my favorite too.";      }  }  void AddNewDessert(object sender, EventArgs e) {     if (NewDessert.Value != "") {         Dessert.Items.Add(NewDessert.Value);      }  }  </script>  <html>  <head>  <title>HtmlControl Select</title>  </head>  <body>  <form runat=server>    Select a dessert:<br>  <select  runat="server" />  <input type="button" runat="server" Value="Submit" OnServerClick="PickDessert">  <p>  If you don't see <b>your</b> favorite dessert in the list, you can add it:<br>  <input type="text"  runat="server">  <input type="button" runat="server" Value="Add" OnServerClick="AddNewDessert">  <p>  <span  runat="server"></span>  </form>  </body>  </html> 

In Figure 6.14, you will see that you can select an option from the Select box, and if you don't see an option that suits you, you can add whatever value you want to the Select box. You do so by using an OnServerClick event and the Item.Add() method discussed earlier.

Figure 6.14. The HtmlSelect control gives you a way to manipulate Select boxes programmatically.
graphics/06fig14.gif

HtmlTable, HtmlTableRow, HtmlTableCell

These controls are a gas. You can do just about anything to adjust all the properties of a table, table row, or table cell with these three controls. What I'm going to do is provide you with all the properties and a few of the methods of these controls (in Tables 6.13, 6.14, and 6.15), and then give you a big, fat example and let you have at it.

Table 6.13. HtmlTable Object Properties

Property

Description

Align

Gets or Sets the value of the align attribute (that is, align="center").

BgColor

Gets or Sets the table's Background color.

Border

Gets or Sets how wide a table's border is in pixels.

BorderColor

Gets or Sets the color of the table's border.

CellPadding

Gets or Sets the value of the table's cellpadding attribute.

CellSpacing

Gets or Sets the value of the table's cellspacing attribute.

Height

Gets or Sets the value of the table's height attribute.

Rows

Instance of the HtmlTableRowCollection, exposing its properties and methods.

Width

Gets or Sets the value of the table's width attribute.

Table 6.14. HtmlTableRow Object Properties

Property

Description

Align

Gets or Sets the value of the row's align attribute (that is, align="center").

BgColor

Gets or Sets the background color of the row.

BorderColor

Gets or Sets the color of the row's border.

Cells

Instance of the HtmlTableCellCollection, exposing its properties and methods.

Height

Gets or Sets the value of the row's height attribute.

VAlign

Gets or Sets the vertical alignment of the contents of the cells of the row.

Table 6.15. HtmlTableCell Object Properties

Property

Description

Align

Gets or Sets the value of the cell's align attribute (that is, align="center").

BgColor

Gets or Sets the background color of the cell.

BorderColor

Gets or Sets the color of the cell's border.

ColSpan

Gets or Sets how many columns the cell spans across.

Height

Gets or Sets the value of the row's height attribute.

NoWrap

Gets or Sets a Boolean value that defines whether text within a cell should wrap. False is the default.

RowSpan

Gets or Sets how many rows the cell spans across.

VAlign

Gets or Sets the vertical alignment of the contents of a cell.

Width

Gets or Sets the value of the row's width attribute.

These properties and methods are exposed through HtmlTable's row property. The HtmlTableRows cell property gives you a golf bag full of clubs to create and manipulate tables. Manipulating a table this way isn't a method I use often, but it's nice to have for situations where complete programmatic control over a table solves problems.

The following is an example of creating a table, then manipulating its properties programmatically. You can also create a table programmatically with the methods and properties available through the HtmlTable's row property and the HtmlTableRows cell property, but I don't do that here. I do use the Add() method to dynamically add a row of cells to the table if the Add Row check box is checked.

Visual Basic .NET html_table_vb.aspx
<%@ page language="vb" runat="server"%>  <script  runat=server>  sub Page_Load(sender As Object, e As EventArgs)      dim OurArray() as Integer = {0,1,2,3,5,6,7,8,9,10}      dim OurColorArray() as String = {"Red", "Blue", "Green", "Orange", "Cyan"}      if not IsPostBack          OurCellPaddingSelect.DataSource = OurArray          OurCellSpacingSelect.DataSource = OurArray          OurBorderSelect.DataSource = OurArray          OurBGColorSelect.DataSource = OurColorArray          OurBorderColorSelect.DataSource = OurColorArray          DataBind()      else          OurTable.CellSpacing = CInt(OurCellSpacingSelect.Value)          OurTable.CellPadding = CInt(OurCellPaddingSelect.Value)          OurTable.Border = Cint(OurBorderSelect.Value)          OurTable.BGColor = OurBGColorSelect.Value          OurTable.BorderColor = OurBorderColorSelect.Value          if (OurCheckBox.Checked) then              dim cell as HtmlTableCell              dim row as HtmlTableRow              row = new HtmlTableRow()              cell = new HtmlTableCell()              cell.InnerText = "Pie"              row.Cells.Add(cell)              cell = new HtmlTableCell()              cell.InnerText = "Cookies"              row.Cells.Add(cell)              cell = new HtmlTableCell()              cell.InnerText = "Ice Cream"              row.Cells.Add(cell)              OurTable.Rows.Add(row)          end if      end if  end sub  </script>  <html>  <head>  <title>HtmlControl Table</title>  </head>  <body>  <form runat=server>  <table>  <tr>  <td>Table Cell Padding:</td>  <td><select  runat="server" /></td>  </tr>  <tr>  <td>Table Cell Spacing:</td>  <td><select  runat="server" /></td>  </tr>  <tr>  <td>Table Borders:</td>  <td><select  runat="server" /></td>  </tr>  <tr>  <td>Table BG Color:</td>  <td><select  runat="server" /></td>  </tr>  <tr>  <td>Table Border Color:</td>  <td><select  runat="server" /></td>  </tr>    <tr>  <td>Insert Row:</td>  <td><input type="checkbox" runat="server"  /></td>  </tr>  <tr>  <td colspan="2"><input type="submit" value="Submit" runat="server" /></td>  </tr>  </table>  <br><br>  <table  runat="server">  <tr>  <td>Cell 1</td>  <td>Cell 2</td>  <td>Cell 3</td>  </tr>  <tr>  <td>Cell 4</td>  <td>Cell 5</td>  <td>Cell 6</td>  </tr>  <tr>  <td>Cell 7</td>  <td>Cell 8</td>  <td>Cell 9</td>  </tr>  </table>  </font>  </form>  </body>  </html> 
C# html_table_cs.aspx
<%@ page language="c#" runat="server"%>  <script  runat=server>  void Page_Load(object sender, EventArgs e)  {     int[] OurArray  = {0,1,2,3,5,6,7,8,9,10};      string[] OurColorArray = {"Red", "Blue", "Green", "Orange", "Cyan"};      if (!IsPostBack) {         OurCellPaddingSelect.DataSource = OurArray;          OurCellSpacingSelect.DataSource = OurArray;          OurBorderSelect.DataSource = OurArray;          OurBgColorSelect.DataSource = OurColorArray;          OurBorderColorSelect.DataSource = OurColorArray;          DataBind();      }      else {         OurTable.CellSpacing = int.Parse(OurCellSpacingSelect.Value);          OurTable.CellPadding = int.Parse(OurCellPaddingSelect.Value);          OurTable.Border = int.Parse(OurBorderSelect.Value);          OurTable.BgColor = OurBgColorSelect.Value;          OurTable.BorderColor = OurBorderColorSelect.Value;          if (OurCheckBox.Checked) {              HtmlTableCell cell;              HtmlTableRow row;              row = new HtmlTableRow();              cell = new HtmlTableCell();              cell.InnerText = "Pie";              row.Cells.Add(cell);              cell = new HtmlTableCell();              cell.InnerText = "Cookies";              row.Cells.Add(cell);              cell = new HtmlTableCell();              cell.InnerText = "Ice Cream";              row.Cells.Add(cell);              OurTable.Rows.Add(row);          }      }  }  </script>  <html>  <head>  <title>HtmlControl Table</title>  </head>  <body>  <form runat=server>  <table>  <tr>  <td>Table Cell Padding:</td>  <td><select  runat="server" /></td>  </tr>  <tr>  <td>Table Cell Spacing:</td>  <td><select  runat="server" /></td>  </tr>  <tr>  <td>Table Borders:</td>  <td><select  runat="server" /></td>  </tr>  <tr>  <td>Table BG Color:</td>  <td><select  runat="server" /></td>  </tr>  <tr>  <td>Table Border Color:</td>  <td><select  runat="server" /></td>  </tr>    <tr>  <td>Insert Row:</td>  <td><input type="checkbox" runat="server"  /></td>  </tr>  <tr>  <td colspan="2"><input type="submit" value="Submit" runat="server" /></td>  </tr>  </table>  <br><br>  <table  runat="server">  <tr>  <td>Cell 1</td>  <td>Cell 2</td>  <td>Cell 3</td>  </tr>  <tr>  <td>Cell 4</td>  <td>Cell 5</td>  <td>Cell 6</td>  </tr>  <tr>  <td>Cell 7</td>  <td>Cell 8</td>  <td>Cell 9</td>  </tr>  </table>  </font>  </form>  </body>  </html> 

In Figure 6.15, you will see a stunningly attractive HTML table (ah? yeah!) that demonstrates how to manipulate your HtmlTable control. I also used the Add() method to add both rows and cells (and my favorite dessert) to the table.

Figure 6.15. The HtmlTable, HtmlTableRow, and HtmlTableCell give you the ability to treat a table as an object and manipulate its properties.
graphics/06fig15.gif

HtmlTextArea

The HtmlTextArea is pretty darn similar to the HtmlTextBox, except that it has properties to control the size of the box. Table 6.16 lists the HtmlTextArea's additional properties.

Table 6.16. HtmlTextArea Object Properties

Property

Description

Cols

Gets or Sets the width in characters of a textarea.

Name

Gets or Sets the unique identifier name of the textarea.

Rows

Gets or Sets the number of rows based on the character height of a textarea.

Value

Gets or Sets the text entered into the textarea.

Visual Basic .NET html_textarea_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  sub Page_Load(Sender as Object, e as EventArgs)      if Not IsPostBack Then          OurTextArea.Rows = 5          OurTextArea.Cols = 50      else          OurSpan.InnerHtml = "<b>You Wrote:</b> <i>" + OurTextArea.Value + "</i>"      end if  end sub  </script>  <html>  <head>  <title>HtmlControl TextArea</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <h2>In 250 words or less, please describe why your favorite dessert is the best.</h2>  <textarea  runat="server" />  <br><br>  <input type="Submit" value="Submit">  <br><br>  <span  runat="server"/>  </form>  </body>  </html> 
C# html_textarea_cs.aspx
<%@ page language="cs" runat="server"%>  <script runat=server>  void Page_Load(object o, EventArgs e){     if (!IsPostBack) {         OurTextArea.Rows = 5;          OurTextArea.Cols = 50;      }      else {         OurSpan.InnerHtml = "<b>You Wrote:</b> <i>" + OurTextArea.Value + "</i>";      }  }  </script>  <html>  <head>  <title>HtmlControl TextArea</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <div align="center">  <h2>In 250 words or less, please describe why your favorite dessert is the best.</h2>  <textarea  runat="server" />  <br><br>  <input type="Submit" value="Submit">  <br><br>  <span  runat="server"/>  </div>  </form>  </body>  </html> 

You can see the results of this example is Figure 6.16. The Cols and Rows properties are set during the Page_Load event, and then the textarea's value is retrieved when the page is posted back.

Figure 6.16. The HtmlTextArea behaves the same way an HtmlTextBox does, except you can control the size of the box through the Cols and Rows attributes.
graphics/06fig16.gif


   
Top


ASP. NET for Web Designers
ASP.NET for Web Designers
ISBN: 073571262X
EAN: 2147483647
Year: 2005
Pages: 94
Authors: Peter Ladka

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net