Using Rich Controls


In the following sections, you learn how to use three of the more feature-rich controls in the ASP.NET framework. You learn how to use the Calendar control to display interactive calendars, the AdRotator control to display rotating banner advertisements, and the HTMLInputFile control to accept file uploads.

Displaying Interactive Calendars with the Calendar Control

You can use the ASP.NET Calendar control to display an interactive calendar on a page. This control enables you to select particular days, weeks, or months. You can also display custom content on each day. All the properties, methods , and events of this control are listed in Table 4.3.

Table 4.3. Calendar Properties, Methods, and Events

Properties

Description

CellPadding

Specifies the number of pixels between the contents of a cell and its border.

CellSpacing

Specifies the number of pixels between cells .

DayNameFormat

Sets the format of the day names . Possible values are FirstLetter , FirstTwoLetters , Full , and Short ; the default is Short .

FirstDayOfWeek

Specifies the day of the week that is displayed in the calendar's first column. Possible values are Default , Friday , Monday , Saturday , Sunday , Thursday , Tuesday , and Wednesday ; the default is Default , which uses the server's local settings.

NextMonthText

If ShowNextPrevMonth is True , specifies the text for the Next Month hyperlink.

NextPrevFormat

Specifies the format of the Next and Previous hyperlinks . Possible values are CustomText , FullMonth , and ShortMonth ; the default is CustomText .

PrevMonthText

If ShowNextPrevMonth is True , specifies the text for the Previous Month hyperlink.

SelectedDate

Contains a DateTime value that specifies the highlighted day. The default value is TodaysDate .

SelectedDates

Contains a collection of DateTime items that represent the highlighted days on the calendar.

SelectionMode

Determines whether days, weeks, or months can be selected. Possible values are Day , DayWeek , DayWeekMonth , and None ; the default is Day .

SelectMonthText

Contains HTML text displayed for selecting months when SelectionMode has the value DayWeekMonth .

SelectWeekText

Contains HTML text displayed for selecting weeks when SelectionMode has the value DayWeek or DayWeekMonth .

ShowDayHeader

If True , displays the names of the days of the week.

ShowGridLines

If True , renders the calendar with lines around the days.

ShowNextPrevMonth

If True , displays Next Month and Previous Month links.

ShowTitle

If True , displays the calendar's title.

TitleFormat

Determines how the month name appears in the title bar. Possible values are Month and MonthYear .

TodaysDate

Specifies a DateTime value that sets the calendar's current date.

VisibleDate

Specifies a DateTime value that sets the month to display.

Methods

Description

OnDayRender

Raises the DayRender event.

OnSelectionChanged

Raises the SelectionChanged event.

OnVisibleMonthChanged

Raises the VisibleMonthChanged event.

Events

Description

DayRender

Raised before each day cell is rendered on the calendar.

SelectionChanged

Raised when a new day, month, or week is selected.

VisibleMonthChanged

Raised by clicking the Next Month or Previous Month link.

Typical uses for the Calendar control include displaying a schedule of events. You can customize the appearance of each cell in the calendar as it is displayed. You can even display a hyperlink to more information within each calendar day.

Another common use of the Calendar control is scheduling. Because you can select particular days, weeks, or months on the calendar, you can use the control to reserve dates for meetings or events.

A complex calendar can be added to a page with very few lines of code. For example, Listing 4.14 displays the default calendar displayed by the Calendar control (see Figure 4.8).

Listing 4.14 Calendar.aspx
 <html> <head><title>calendar.aspx</title></head> <body> <form Runat="Server"> <asp:Calendar   Runat="Server" /> </form> </body> </html> 

The C# version of this code can be found on the CD-ROM.

Figure 4.8. Calendar control with default properties.

graphics/04fig08.jpg

Customizing the Appearance of the Calendar Control

You can customize the appearance of the Calendar control in three ways: You can use the formatting properties common to all controls, you can use the general formatting properties of the Calendar control, or you can apply one or more custom style objects to the control.

The Calendar control supports all the common Web control formatting properties described in Chapter 2. For example, you can modify Calendar properties such as BackColor , ForeColor , Border , Font , Height , and Width by modifying the base Web control formatting properties.

NOTE

All the common Web control formatting properties are listed under the base Web control properties in Appendix C, "Web Control Reference."


The page contained in Listing 4.15 illustrates how you can modify several of these properties (see Figure 4.9 for the output).

Listing 4.15 CalendarBaseFormatting.aspx
 <html> <head><title>CalendarBaseFormatting.aspx</title></head> <body> <form Runat="Server"> <asp:Calendar   Width="100%"   BackColor="blue"   ForeColor="Yellow"   Font-Name="Script"   Font-Size="24pt"   Font-Bold="True"   Runat="Server" /> </form> </body> </html> 

The C# version of this code can be found on the CD-ROM.

Figure 4.9. A calendar with different base Web control formatting properties.

graphics/04fig09.jpg

You also can modify the general formatting properties of the Calendar control itself. Examples of these properties are ShowGridLines , NextMonthText , PrevMonthText , and TitleFormat . You can find a list of all these properties in Table 4.3.

To change the way the next and previous month links are displayed, for example, you can modify the NextPrevFormat , NextMonthText , PrevMonthText , and ShowNextPrevMonth properties. You can even use images for the link to the next and previous months by setting the properties like this:

 
 <asp:Calendar   ID="myCal"   PrevMonthText="<img src='prev.gif'>"   NextMonthText="<img src='next.gif'>"   Runat="Server" /> 

To modify the way the list of weekdays appears in the calendar, modify the DayNameFormat property. When this property has the value FirstLetter , only the first letter of each day is shown. When this property has the value FirstTwoLetters , only the first two letters of each day are shown. When this property has the value Full , the full day name is shown. When this property has the value Short , three letters are shown for each day.

You also can modify the format of a Calendar control by applying any one of several style objects to the calendar. The Calendar control supports the style objects listed in Table 4.4.

Table 4.4. Calendar Style Objects

Object

Description

DayHeaderStyle

The style of the weekdays listed at the top of the calendar

DayStyle

The style applied to each day in the calendar

NextPrevStyle

The style applied to the next and previous month links

OtherMonthDayStyle

The style applied to days from other months that appear in the current month

SelectedDayStyle

The style applied to the currently selected day

SelectorStyle

The style applied to the link for selecting the week or month

TitleStyle

The style applied to the calendar's title bar

TodayDayStyle

The style applied to the current date

WeekendDayStyle

The style applied to weekend days

All the style objects, with the exception of the TitleStyle object, support the properties of the TableItemStyle style class. (The properties of this class are listed in Appendix C.) The TitleStyle object supports all the styles of the base style class (also listed in Appendix C).

Suppose that you want to display most days in blue, but show weekends in green, today in yellow, and the selected date in orange. You can do so by modifying the style objects. Listing 4.16 contains a (very ugly) Calendar control formatted with these properties.

Listing 4.16 CalendarStyle.aspx
 <html> <head><title>CalendarStyle.aspx</title></head> <body> <form Runat="Server"> <asp:Calendar   DayStyle-BackColor="Blue"   WeekendDayStyle-BackColor="Green"   TodayDayStyle-BackColor="Yellow"   SelectedDayStyle-BackColor="Orange"   Runat="Server" /> </form> </body> </html> 

The C# version of this code can be found on the CD-ROM.

Selecting Days, Weeks, and Months with the Calendar Control

By default, the Calendar control enables you to pick a particular day on the calendar. However, you can modify the properties of the Calendar control so that it enables you to select weeks or months. You can even set the Calendar control so that it does not allow you to pick anything.

To pick weeks or months, modify the SelectionMode property. You can assign the values Day , DayWeek , DayWeekMonth , or None to this property. For example, the value DayWeekMonth enables you to select either a day, week, or month.

After you modify the SelectionMode property to enable week or month selection, you can modify the SelectWeekText and SelectMonthText properties to display different links for selecting the day or month. You can even assign images to these properties by using syntax like this:

 
 <asp:Calendar   ID="myCal"   SelectionMode="DayWeekMonth"   SelectWeekText="<img src='selectWeek.gif'>"   SelectMonthText="<img src='selectMonth.gif'>"   Runat="Server" /> 

To determine the dates that have been selected on the calendar, use the SelectionChanged event. When this event is raised, you can use the SelectedDate property to determine what date is selected or the SelectedDates property to determine what dates are selected.

The page in Listing 4.17, for example, demonstrates how you can retrieve and display the dates selected on a calendar (see Figure 4.10).

Listing 4.17 CalendarSelected.aspx
 <Script Runat="Server"> Sub Calendar_SelectionChanged( s As Object, e As EventArgs )   Dim dtmDate As DateTime   lblDates.Text = "<h2>You selected the following date(s):</h2>"   For Each dtmDate in calCalendar.SelectedDates     lblDates.Text &= "<li>" & dtmDate.ToString( "D" )   Next End Sub </Script> <html> <head><title>CalendarSelected.aspx</title></head> <body> <form Runat="Server"> <asp:Calendar   id="calCalendar"   SelectionMode="DayWeekMonth"   SelectWeekText="Select Week"   SelectMonthText="Select Month"   OnSelectionChanged="Calendar_SelectionChanged"   Runat="Server" /> <asp:Label   ID="lblDates"   Runat="Server" /> </form> </body> </html> 

The C# version of this code can be found on the CD-ROM.

Figure 4.10. Selecting calendar dates.

graphics/04fig10.jpg

When a new day, week, or month is selected, the SelectionChanged event is raised. This event is handled in Listing 4.17 by a subroutine named Calendar_SelectionChanged . This subroutine loops through the collection of dates represented by the Calendar control's SelectedDates property. Each item in this collection is a DateTime .

Rendering Calendar Days

Whenever the Calendar control renders a particular day, the control raises the DayRender event. You can write a subroutine that handles this event and display custom content on each calendar day.

To capture the DayRender event, create a subroutine with these parameters:

 
 Sub Calendar_DayRender( s As Object, e As DayRenderEventArgs ) End Sub 

The second parameter passed to the subroutine, DayRenderEventArgs , has a number of properties that you can use in your code. These properties are listed in Table 4.5.

Table 4.5. DayRenderEventArgs Properties

Properties

Description

Cell

The table cell containing the day being rendered.

Cell.ColumnSpan

An integer value indicating the number of table columns the cell should span.

Cell.HorizontalAlign

The cell's horizontal alignment. Possible values are Center , Justify , Left , NotSet , and Right .

Cell.RowSpan

An integer value indicating the number of table rows the cell should span.

Cell.Text

The text that appears in the cell.

Cell.VerticalAlign

The cell's vertical alignment. Possible values are Bottom , Middle , NotSet , and Top .

Cell.Wrap

If True , the contents of the cell word-wrap.

Day

A CalendarDay object that represents the day being rendered.

Day.Date

A DateTime value that represents the day being rendered.

Day.DayNumberText

A string that represents the number of the day being rendered.

Day.IsOtherMonth

If True , the day being rendered is not a member of the current month.

Day.IsSelectable

If True , this day can be selected.

Day.IsSelected

If True , this day is selected.

Day.IsToday

If True , this day is the current day.

Day.IsWeekend

If True , this day is a Saturday or Sunday.

Listing 4.18 illustrates how you can use the DayRender event to display a daily horoscope in a Calendar control.

Listing 4.18 CalendarHoroscope.aspx
 <%@ Import Namespace="System.Drawing" %> <Script Runat="Server">   Dim RanNum As New Random( 23 )   Sub Calendar_RenderDay( s As Object, e As DayRenderEventArgs )     Dim ctlCell As TableCell     Dim strHoroscope As String     ctlCell = e.Cell     Select Case RanNum.Next( 4 )     Case 0       strHoroscope = "Good things will happen today!"       ctlCell.BackColor = Color.FromName( "Green" )     Case 1       strHoroscope = "You're doomed! Hide in bed!"       ctlCell.BackColor = Color.FromName( "Red" )     Case 2       strHoroscope = "Something unexpected will happen"     Case 3       strHoroscope = "Look before you leap!"     End Select     ctlCell.Controls.Add( New LiteralControl( "<p>" ) )     ctlCell.Controls.Add( New LiteralControl( strHoroscope ) )   End Sub </Script> <html> <head><title>CalendarHoroscope.aspx</title></head> <body> <h1>Horoscope:</h1> <form Runat="Server"> <asp:Calendar   Width="100%"   CellPadding="10"   ShowGridLines="True"   SelectionMode="None"   OnDayRender="Calendar_RenderDay"   Runat="Server" /> </form> </body> </html> 

The C# version of this code can be found on the CD-ROM.

The Calendar_RenderDay subroutine is called for each day rendered on the calendar. This subroutine randomly selects from four possible horoscopes and displays one for the particular day being rendered (see Figure 4.11).

Figure 4.11. Handling the DayRender event.

graphics/04fig11.jpg

Notice how the Controls collection of the calendar cell is used. To add new content to a day, you add new controls to the Controls collection of a calendar cell. In Listing 4.18, you add two LiteralControl controls: One LiteralControl represents an HTML paragraph break, and the other represents the text of the horoscope.

NOTE

You can also add text to a particular calendar cell by using the TableCell 's Text property. This works fine for plain text or HTML content. However, you cannot use the Text property to add ASP.NET controls, such as TextBox controls.


Creating an Interactive Meeting Scheduler

In this section, you build a more complex application using the Calendar control. You create a Web application that enables you to add notes to any day on the calendar and save the notes between visits . The complete code for this application is contained in Listing 4.19.

The ASP.NET page in Listing 4.19 contains Calendar , TextBox , and Button controls. If you want to add a note to a date, you select the date on the calendar, enter the note in the text box, and click the Save Changes button.

Every date on the calendar is represented by a two-dimensional array named arrCalendar . The first index of the array represents the month, and the second index represents the day.

The Calendar_RenderDay subroutine is called for each day that is rendered on the calendar. This subroutine displays the day with an orange background color if a note is associated with the day.

When you click Save Changes, the contents of the arrCalendar array are saved to disk. This is accomplished in the btnSave_Click subroutine. The array is saved to a file named schedule.bin located in the root of the C: drive.

If you save changes and return to the page on a later date, the notes are preserved. When the page is first loaded, the notes are retrieved from the schedule.bin file saved on disk. After the notes are loaded the first time, they are subsequently retrieved from the cache to improve performance.

NOTE

Since the page in Listing 4.19 writes to the file system, you'll need to grant write permissions to the ASPNET user account to write to the directory containing the schedule.bin file. For more information on the ASPNET user account see Chapter 20, "Using Windows-Based Authentication."


Listing 4.19 CalendarSchedule.aspx
 <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Runtime.Serialization" %> <%@ Import Namespace="System.Runtime.Serialization.Formatters.Binary" %> <%@ Import Namespace="System.Drawing" %> <Script Runat="Server"> Dim arrCalendar( 13, 32 ) As String ' Get schedule from cache or disk Sub Page_Load   Dim strmFileStream As FileStream   Dim fmtrBinaryFormatter As BinaryFormatter   If Cache( "arrCalendar" ) Is Nothing Then     If File.Exists( "c:\schedule.bin" ) Then       strmFileStream = _         New FileStream( "c:\schedule.bin", FileMode.Open )       fmtrBinaryFormatter = New BinaryFormatter       arrCalendar = _         CType( fmtrBinaryFormatter.Deserialize( strmFileStream ), Array )       strmFileStream.Close()       Cache( "arrCalendar" ) = arrCalendar     End If   Else     arrCalendar = Cache( "arrCalendar" )   End If End Sub ' Save schedule to file Sub btnSave_Click( s As Object, e As EventArgs )   Dim dtmDate As DateTime   Dim strmFileStream As FileStream   Dim fmtrBinaryFormatter As BinaryFormatter   dtmDate = calSchedule.SelectedDate   arrCalendar( dtmDate.Month, dtmDate.Day ) = txtNotes.Text   strmFileStream = _     New FileStream( "c:\schedule.bin", FileMode.Create )   fmtrBinaryFormatter = New BinaryFormatter   fmtrBinaryFormatter.Serialize( strmFileStream, arrCalendar )   strmFileStream.Close()   Cache( "arrCalendar" ) = arrCalendar End Sub ' Pick a date Sub Calendar_SelectionChanged( s As Object, e As EventArgs )   Dim dtmDate As DateTime   dtmDate = calSchedule.SelectedDate   txtNotes.Text = arrCalendar( dtmDate.Month, dtmDate.Day ) End Sub ' Display each calendar day Sub Calendar_RenderDay( s As Object, e As DayRenderEventArgs )   Dim dtmDate As DateTime   Dim ctlCell As TableCell   dtmDate = e.Day.Date   ctlCell = e.Cell   If arrCalendar( dtmDate.Month, dtmDate.Day ) <> "" Then     ctlCell.BackColor = Color.FromName( "Orange" )   End If End Sub </Script> <html> <head><title>CalendarSchedule.aspx</title></head> <body> <form Runat="Server"> <asp:Calendar   id="calSchedule"   Width="100%"   ShowGridLines="True"   OnSelectionChanged="Calendar_SelectionChanged"   OnDayRender="Calendar_RenderDay"   Runat="Server" /> <p> <asp:TextBox   id="txtNotes"   TextMode="MultiLIne"   Columns="50"   Rows="10"   Runat="Server" /> <p> <asp:Button   id="btnSave"   Text="Save Changes"   OnClick="btnSave_Click"   Runat="Server" /> </form> </body> </html> 

The C# version of this code can be found on the CD-ROM.

Displaying Banner Advertisements with the AdRotator Control

You can use the AdRotator control to randomly display banner advertisements on your Web pages. In most cases, you use the AdRotator control with an advertisement file that contains a list of the properties of banner advertisements to display. All the properties, methods, and events of this control are listed in Table 4.6.

Table 4.6. AdRotator Control Properties, Methods, and Events

Properties

Description

AdvertisementFile

The path to an XML file that contains a list of banner advertisements to display.

KeywordFilter

When set, only those banner advertisements that match the filter are returned.

Target

When you click the banner advertisement, the page is displayed in this window or frame. Possible values are top , new , child , self , parent , and blank .

Methods

Description

OnAdCreated

Raises the AdCreated event.

Events

Description

AdCreated

Raised after an advertisement is retrieved from the advertisement file and before the banner advertisement is rendered.

The Advertisement File is an XML file with the following format:

 
 <Advertisements>    <Ad>       <ImageUrl>URL of image to display</ImageUrl>       <TargetUrl> URL of page to link to </TargetUrl>       <AlternateText>          Text to show as ToolTip        </AlternateText>       <Keyword>keyword used to filter</Keyword>       <Impressions>relative weighting of ad</Impressions>    </Ad> </Advertisements> 

The file enables you to specify the properties for each banner advertisement described in Table 4.7:

  • ImageUrl ” The URL of the image to display for the advertisement. It can be either a relative or absolute path.

  • NavigateUrl ” The page you go to when you click an advertisement.

  • AlternateText ” The alternative text that is displayed for browsers that do not support images. This property is also commonly used to display ToolTip text.

  • Keyword ” An optional keyword that you can use to categorize the banner advertisement. It can be used with the KeywordFilter property to display different categories of advertisements from the file.

  • Impressions ” The relative frequency that a particular advertisement should be shown in relation to other advertisements in the file. All things being equal, the higher this number, the more times this advertisement will be shown.

All the preceding properties are optional except ImageUrl . For example, if you do not specify a NavigateUrl , the banner advertisement is displayed without a link.

TIP

You can add your own custom properties to the advertisement file. For example, you can add a Campaign property that indicates the particular banner campaign for the advertisement. An example of a custom property is included in the next section, "Tracking AdRotator Impressions."


The page contained in Listing 4.20 illustrates how you can use the AdRotator control with an Advertisement File named myAds.xml , which is included in Listing 4.21.

Listing 4.20 AdRotator.aspx
 <html> <head><title>AdRotator.aspx</title></head> <body> <form Runat="Server"> <asp:AdRotator   AdvertisementFile="myAds.xml"   Runat="Server" /> </form> </body> </html> 

The C# version of this code can be found on the CD-ROM.

Listing 4.21 myAds.xml
 <Advertisements>    <Ad>       <ImageUrl>AspWorkshopsBanner.gif</ImageUrl>       <NavigateUrl>http://www.AspWorkshops.com</NavigateUrl>       <AlternateText>          Need ASP.NET Training?        </AlternateText>       <Impressions>2</Impressions>    </Ad>    <Ad>       <ImageUrl>SuperexpertBanner.gif</ImageUrl>       <NavigateUrl>http://www.superexpert.com</NavigateUrl>       <AlternateText>          Click here to visit Superexpert.com!        </AlternateText>       <Impressions>1</Impressions>    </Ad> </Advertisements> 

The C# version of this code can be found on the CD-ROM.

Tracking AdRotator Impressions

If you add a subroutine to handle the AdCreated event, you can track the number of times each banner advertisement is displayed. You can use this subroutine to record advertisement statistics to a database table, an XML file, or the file system.

When the AdCreated event is raised, an instance of the AdCreatedEventArgs class is passed to the subroutine that handles the event. The properties of the AdCreatedEventArgs class are listed in Table 4.8.

Table 4.8. AdCreatedEventArgs Properties

Properties

Description

AdProperties

A collection of all the attributes for the current advertisement retrieved from the advertisement file. This collection includes any custom properties in the advertisement file.

AlternateText

Gets or sets any alternative text for the advertisement.

ImageUrl

Gets or sets the path to the image for the current advertisement.

NavigateUrl

Gets or sets the path to the page you go to when you click the current advertisement.

For example, the page in Listing 4.22 records statistics on the number of times each advertisement is displayed to the file system. The page uses the advertisement file in Listing 4.23. Each advertisement in the advertisement file has a custom Campaign property.

When the AdRotator in Listing 4.22 displays an advertisement, the AdRotator_ AdCreated subroutine updates the statistics for the advertisement. For example, if the AspWorkshops advertisement is displayed, then the number of impressions for this advertisement is recorded to a file named AspWorkshops.imp . The name of the file _corresponds to the Campaign property in the advertisement file.

Listing 4.22 AdRotatorImpressions.aspx
 <%@ Import Namespace="System.IO" %> <Script runat="Server"> Sub AdRotator_AdCreated( s As Object, e As AdCreatedEventArgs )   Dim intImpressions As Integer = 0   Dim strFileName As String   Dim strmStreamReader As StreamReader   Dim strmStreamWriter As StreamWriter   ' Assign file name   strFileName = e.AdProperties( "Campaign" ).Trim & ".imp"   If strFileName = "" Then     strFileName = "default.imp"   End If   ' Read current impressions   If File.Exists( MapPath( strFileName ) ) Then     strmStreamReader = File.OpenText( MapPath( strFileName ) )     intImpressions = Cint( strmStreamReader.ReadLine )     strmStreamReader.Close   End If   ' Write current impressions   strmStreamWriter = File.CreateText( MapPath( strFileName ) )   strmStreamWriter.Write( intImpressions + 1 )   strmStreamWriter.Close End Sub </Script> <html> <head><title>AdRotatorImpressions.aspx</title></head> <body> <form Runat="Server"> <asp:AdRotator   AdvertisementFile="AdCampaigns.xml"   OnAdCreated="AdRotator_AdCreated"   Runat="Server" /> </form> </body> </html> 

The C# version of this code can be found on the CD-ROM.

Listing 4.23 AdCampaigns.xml
 <Advertisements>    <Ad>       <Campaign>AspWorkshops</Campaign>       <ImageUrl>AspWorkshopsBanner.gif</ImageUrl>       <NavigateUrl>http://www.AspWorkshops.com</NavigateUrl>       <AlternateText>          Need ASP.NET Training?        </AlternateText>       <Impressions>2</Impressions>    </Ad>    <Ad>       <Campaign>Superexpert</Campaign>       <ImageUrl>SuperexpertBanner.gif</ImageUrl>       <NavigateUrl>http://www.superexpert.com</NavigateUrl>       <AlternateText>          Click here to visit Superexpert.com!        </AlternateText>       <Impressions>1</Impressions>    </Ad> </Advertisements> 

The C# version of this code can be found on the CD-ROM.

Accepting File Uploads with the HTMLInputFile Control

In many situations, you need to enable the users of your Web site to upload files to your Web server. For example, you might want to create a form that provides your users with a means to upload images if you are constructing an image library. Or you might want to build a central document repository to store Microsoft Word documents.

You can use the HTMLInputFile control to enable users to transfer any type of file from their hard drive to your Web site. You can upload images, HTML files, Microsoft Word documents, MPEG files, or video files with the HTMLInputFile control.

All the properties, methods, and events of this control are listed in Table 4.9.

Table 4.9. HTMLInputFile Properties, Methods, and Events

Properties

Description

Accept

Specifies a comma-delimited list of the MIME types of files acceptable for upload. For example, use image/gif for GIF files or image/* for any type of image file.

MaxLength

Specifies the maximum number of characters that can be entered into the upload text box.

PostedFile

Returns the file uploaded by the user.

Size

Indicates the size of the upload text box.

Methods

Description

None

 

Events

Description

None

 

The page in Listing 4.24 illustrates how you can create a simple upload form that enables you to upload an image file (GIF file). Any file uploaded with this form is saved with the name NewFile.gif in a folder named c:\uploads (you'll need to create this folder yourself).

Listing 4.24 HtmlInputFile.aspx
 <Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs )   inpFileUp.PostedFile.SaveAs( "c:\Uploads\NewFile.gif" ) End Sub </Script> <html> <head><title>HtmlInputFile.aspx</title></head> <body> <form EncType="multipart/form-data" Runat="Server"> <input id="inpFileUp" Type="File" Runat="Server"> <p> <asp:Button   Text="Upload File!"   OnClick="Button_Click"   Runat="Server" /> </form> </body> </html> 

The C# version of this code can be found on the CD-ROM.

The HTMLInputFile is an HTML control (not a Web control). The control is declared on the page with the following tag:

 
 <input id="fileUp" Type="File" Runat="Server"> 

On Internet Explorer (version 3.02 and higher), or Netscape Navigator (version 3.0 or higher), this tag renders a text box field accompanied by a Browse button that enables you to select a file to upload from your hard drive (see Figure 4.12).

Figure 4.12. Creating a file upload form with the HTMLInputFile control.

graphics/04fig12.jpg

If you include an HTMLInputFile control in a form, you must change the default encoding format used by the form. You can change the encoding format by modifying the form's EncType property. The form in Listing 4.24 is created with the following tag:

 
 <form EncType="multipart/form-data" Runat="Server"> 

When the button is clicked and the file is uploaded, the Button_Click subroutine saves the file to disk. The file is saved with the following statement:

 
 inpFileUp.PostedFile.SaveAs( "c:\Uploads\NewFile.gif" ) 

The PostedFile property refers to whatever file was uploaded. Technically, this property refers to an instance of the HttpPostedFile class. Here, you are calling the SaveAs() method of the HttpPostedFile class to save the uploaded file to disk.

The properties and methods of the HttpPostedFile class are listed in Table 4.10.

Table 4.10. HttpPostedFile Properties, Methods, and Events

Properties

Description

ContentLength

Specifies the size of the uploaded file in bytes

ContentType

Specifies the MIME content type of the uploaded file

FileName

Specifies the full path of the uploaded file on the client's machine

InputStream

Returns a stream that represents the raw contents of the uploaded file

Methods

Description

SaveAs

Saves the uploaded file to disk

Events

Description

None

 

You can use the properties of the HttpPostedFile class to retrieve additional information about an uploaded file. For example, you can use the ContentLength property to check the size of a file and not save it when the file is too big. You can use the ContentType property to determine whether an uploaded file is an image file, a Microsoft Word document, or some other type of file.



ASP.NET Unleashed
ASP.NET 4 Unleashed
ISBN: 0672331128
EAN: 2147483647
Year: 2003
Pages: 263

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