Using the IDE

The Visual Studio .NET (VS.NET) integrated development environment (IDE) offers a rich feature set with tremendous productivity aids, such as:

  • IntelliSense, which pops up with help on every method and function call as you type

  • Integrated dynamic help

  • Integrated build and compile support

  • Integrated support for source control software

  • Built-in task list

  • A modern interface with a tabbed page metaphor for code and layout screens, dockable toolbars, a Solution Explorer, and Properties windows

  • WYSIWYG (What You See Is What You Get) design of Windows and Web Forms

  • Drag-and-drop form design, which allows you to drag controls from the Toolbox and position them on the design surface

Visual Studio .NET will save you a great deal of typing and will generate a tremendous amount of boiler plate code. This can be a mixed blessing, however, because the generated code can add a lot of clutter to your files.

In addition, VS.NET creates solutions and projects with directories and files in a number of places on your hard disk, and it can be confusing sorting out where everything is. Because VS.NET creates projects and file relationships for you and “saves” you from the details, it can be difficult at first to understand what all the files are and how they relate to one another. This is the chronic problem with helpful systems: if you want to do what they anticipate you will want to do, it is very easy; but if you want to do something unusual, it can be terribly difficult to find your way through the black box.

In this section, you will make the transition from hand-coding ASP.NET applications in a text editor to using the VS.NET IDE. This section will show some of the strong points of the IDE and guide you around some of the pitfalls.

Getting Started with the IDE

If you have not yet installed the .NET Framework and VS.NET, you should do so now.

In this section you will rewrite the calendar from Example 5-49 and Example 5-50 in Chapter 5, this time using the Visual Studio .NET IDE. The goal is shown in Figure 6-6.

Calendar demonstration, hand-coded

Figure 6-6. Calendar demonstration, hand-coded

When you open VS.NET, you are presented with a Get Started screen. This screen has a main panel with a list of previously opened projects, an Open Project button for opening a pre-existing project not listed, and a New Project button.

Click on the New Project button. It brings up a dialog box, as shown in Figure 6-7.

New Project dialog box

Figure 6-7. New Project dialog box

You can see that this dialog allows you to select the type of project from VB, C#, C++, and so on. For now, select either Visual C# Projects or Visual Basic Projects. In the right-hand pane are shown several templates. Click on the ASP.NET Web Application icon. These selections will allow us to create a web page using your choice of either C# or VB.NET.

The default name of the new project is WebApplication1. You can enter a different name for the project, but beware that this default name will be scattered throughout the solution, requiring some manual cleanup if you want to remove all traces of it.

Change the Project Name to FirstWebApp by editing the Location field. As you enter the new name, you will see it reflected in the Name field as well as in the label just below the Location field.

The Location field tells you where the project will be created. The default location is in localhost, i.e., the virtual root directory specified in your IIS setup. Typically, localhost is defined as c:inetpubwwwroot. VS.NET creates a separate directory for each project, as the label below the Location field indicates. Because you changed the project name to FirstWebApp, the project will actually be created in the physical directory c:inetpubwwwrootFirstWebApp, although the label in the dialog box will show the project being created in http://localhost/FirstWebApp.

After clicking OK on this dialog box, the program will cook for several moments while it creates the project. Then it will bring you into the design screen, as shown in Figure 6-8.

New Project design screen

Figure 6-8. New Project design screen

Make certain the Toolbox is visible on the screen and that the WebForms tools are displayed. Either Click on the Label tool and drag it out onto the page Design screen or double click on the Label tool. It will now look like the word “Label” surrounded by six small gray handles with a tiny green icon in the upper-left corner. If you click anywhere off of the Label, the gray handles disappear until you click on the Label again to select it.

You can move the Label by selecting it, placing the cursor over the top of the Label until the cursor turns into a four headed arrow, and dragging the control. You can also resize the control by dragging on any of the six handles.

Select the Label. You will see that the Properties box in the lower-right corner of the screen now refers to Label1. Click on the Text field in the Properties box, highlight the existing value, Label, and replace it with the text string: ASP Control Using the IDE. While you’re in the Properties box, change the Font to Bookman Old Style, Bold, Size X-Large. Finally, drag the control handles so that the now larger text string fits on one line. When you are done, the screen should look something like that in Figure 6-9.

First label control

Figure 6-9. First label control

Double-click on the Calendar tool, then move it into position by dragging it with the mouse. Resize it by dragging on one of the corner handles. Rename the calendar’s ID from Calendar1 to cal, to correspond with the code from Example 5-49 and Example 5-50. Now you need to essentially duplicate all the attributes applied to the Calendar control in Example 5-49 and Example 5-50. There are several ways to do this:

  • You can change properties by entering values in the Properties box.

  • In either C# or VB.NET projects, you can enter events by double-clicking on the control. This will open the code-behind page with the code for the default event handler already in place. Once you are looking at the code-behind page, you enter or move to different events differently, depending on the current language:

    • In C# projects, you can enter events by clicking on the Events icon (

      First label control

      ) in the toolbar at the top of the Properties box. Note that the available properties and icons will change depending on which control is currently selected.

    • In VB.NET projects, you can enter events by selecting the control from the drop-down list at the top left of the code-behind page, then selecting the event from the drop-down list at the top right of the code-behind page.

  • You can enter the code directly in the HTML by clicking on the HTML tab at the bottom of the screen.

    Note

    If you are unhappy with the way VS.NET reformats your code you can turn reformatting off. From the menu, choose Tools/Options. In the dialog box under Text Editor:

    • All Languages Tabs. Change the Indenting to Block. Change both Tab Size and Indent Size to 3. Click on Insert spaces.

    • Basic VB Specific. Uncheck “Pretty listing (reformatting) of code.”

    • C# Formatting. Uncheck Automatically format completed constructs and pasted source.

    • HTML/XML Format. Uncheck all the Automatic Formatting Options checkboxes.

    Looking through all the options, there are probably other options you will want to change.

Enter all the properties of the Calendar control in the Properties box. To do this, click on the Calendar control so that the Properties window is showing the properties for Calendar. Then set all the control properties shown in the HTML portion of Example 5-49, listed here in Table 6-8. A typical view of the Properties window is shown in Figure 6-10.

Table 6-8. Calendar properties from Example 5-49

Property

Subproperty

Values

CellPadding

7

CellSpacing

5

DayNameFormat

FirstTwoLetters

FirstDayOfWeek

Monday

NextMonthText

Next >

NextPrevFormat

CustomText

PrevMonthText

< Prev

SelectionMode

DayWeekMonth

ShowGridLines

true

ShowNextPrevMonth

true

DayHeaderStyle

BackColor

Black

Font-Name

Arial Black

ForeColor

White

DayStyle

BackColor

White

ForeColor

Black

Font-Name

Arial

NextPrevStyle

BackColor

DarkGray

ForeColor

Yellow

Font-Name

Arial

OtherMonthDayStyle

BackColor

LightGray

ForeColor

White

Font-Name

Arial

SelectedDayStyle

BackColor

CornSilk

ForeColor

Blue

Font-Name

Arial

Font-Bold

true

Font-Italic

true

SelectorStyle

BackColor

CornSilk

ForeColor

Red

Font-Name

Arial

TitleStyle

BackColor

Gray

ForeColor

White

Font-Name

Arial Black

HorizontalAlign

Left

TodayDayStyle

BackColor

CornSilk

ForeColor

Green

Font-Name

Arial

Font-Bold

true

Font-Italic

false

WeekendDayStyle

BackColor

LavenderBlush

ForeColor

Purple

Font-Name

Arial

Font-Bold

false

Font-Italic

false

When choosing colors, you have the choice of custom, web, or system colors. Custom colors will result in a six digit hexadecimal number that represents the red, green, and blue (RGB) components of the color. To ensure compatibility with the widest range of displays, this example uses predefined colors from the Web tab.

Properties window

Figure 6-10. Properties window

Note that the default value for the NextMonthText property is &gt;, which displays the greater than symbol (>). Similarly, the PrevMonthText property default value is &lt;, which displays the less than symbol (<). In the hand-coded example, these properties were set to "Next >" and "< Prev", respectively. If you enter those exact literals in the Property box, it displays correctly in Design view, but the HTML view indicates a syntax problem. In order to avoid this, you should enter Next &gt; for the NextMonthText property and &lt; Prev for the PrevMonthText property.

Building the Project

Before going any further, build and run the project. There are three possible ways to do this:

  • Click on the Start icon on the VS.NET toolbar.

  • Click on the Debug/Start menu item.

  • Press F5 on your keyboard.

Any of these actions causes VS.NET to build and run the project. A Build window appears at the bottom of the screen with build information. If there are no errors, it goes away and is replaced by two windows named Autos and Call Stack. The use of these windows will be described in Chapter 7. At the same time, a browser window representing your web page will open. It should look something like Figure 6-11.

Calendar control, part 1

Figure 6-11. Calendar control, part 1

This is a fully functional, if somewhat limited, calendar. Click on any of the selection links and you will see that the appropriate day(s) are highlighted. Click on the Previous or Next links and the month changes. Very cool, considering that you have not yet written a single line of code. To see how this works, open the code-behind file.

The code-behind editing window is initially hidden from you. Looking back to Figure 6-9, you see a tab for the page file, WebForm1.aspx, above the design window. Nowhere is there a tab for a code-behind file.

At the bottom of the design window are two tabs, one for Design view (i.e., a graphical layout mode) and one for HTML view (i.e., a text editor). Click on the HTML tab and look at the first line of code. It should look similar to the following default Page directive:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" 
Inherits="FirstWebApp.WebForm1" %>

Notice the Codebehind attribute pointing to the file WebForm1.aspx.cs (or WebForm1.aspx.vb if you chose VB.NET as your development language). This code-behind file has already been created by VS.NET and in fact resides in the same directory as the page file, localhostFirstWebApp, which typically corresponds to the physical directory (c:inetpubwwwrootFirstWebApp ). As described in previous sections, this attribute is used by VS.NET to keep track of which code-behind file to update when changes are made to the page file. The Inherits attribute tells the compiler the name of the class that is being created in the code-behind file.

You can verify that this code-behind file already exists by looking on your hard drive. If you are really curious, open it in Notepad.

To open the code-behind file in VS.NET, do either of the following:

  • Right-click on the web form in either Design mode or HTML editor mode. Select View Code from the menu.

  • Click on the Design tab to see the page in Design mode, then double-click anywhere on the web form.

The C# code-behind file, WebForm1.aspx.cs , should look something like Example 6-15, after all the code regions have been expanded by clicking on the little gray plus signs down the left edge of the code. The equivalent code-behind file in VB.NET will look something like Example 6-16.

As you go back and forth between the Design page and the HTML editor, any changes automatically cause the corresponding change in the code-behind page.

Example 6-15. C# code-behind file, WebForm1.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace FirstWebApp
{
   /// <summary>
   /// Summary description for WebForm1.
   /// </summary>
   public class WebForm1 : System.Web.UI.Page
   {
      protected System.Web.UI.WebControls.Calendar Cal;
      protected System.Web.UI.WebControls.Label Label1;
   
      public WebForm1(  )
      {
         Page.Init += new System.EventHandler(Page_Init);
      }

      private void Page_Load(object sender, System.EventArgs e)
      {
         // Put user code to initialize the page here
      }

      private void Page_Init(object sender, EventArgs e)
      {
         //
         // CODEGEN: This call is required by the ASP.NET Windows Form Designer.
         //
         InitializeComponent(  );
      }

      #region Web Form Designer generated code
      /// <summary>
      /// Required method for Designer support - do not modify
      /// the contents of this method with the code editor.
      /// </summary>
      private void InitializeComponent(  )
      {    
         this.Load += new System.EventHandler(this.Page_Load);

      }
      #endregion
   }
}

Visual Studio .NET has created a namespace based on your project name.

namespace FirstWebApp
{
.
.
.
}

The set of braces in C# indicates that everything contained within the braces is part of the FirstWebApp namespace.

Example 6-16. VB.NET code-behind file, WebForm1.aspx.vb

Public Class WebForm1
    Inherits System.Web.UI.Page
      Protected WithEvents Label1 As System.Web.UI.WebControls.Label
      Protected WithEvents Calendar1 As System.Web.UI.WebControls.Calendar

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent(  )

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) _
                          Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent(  )
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) _
                          Handles MyBase.Load
        'Put user code to initialize the page here
    End Sub

End Class

Notice that there are no Imports statements (equivalent to using statements in C#) in the VB.NET version, nor is a default namespace defined.

In both languages, the WebForm1 class is created, which inherits from System.Web.UI.Page. In C#, this looks like:

public class WebForm1 : System.Web.UI.Page
{

and in VB.NET, the code is:

Public Class WebForm1
    Inherits System.Web.UI.Page

Tip

Some of the lines of code in these examples from Visual Studio .NET are too long to show on the printed page without wrapping. Because line breaks generally do not affect the program in C#, lines are broken arbitrarily for readability in the C# examples. By contrast, line continuation characters are used in the VB.NET examples (although in Visual Studio .NET, the lines are actually single long lines).

You will recall that in the .aspx file the Inherits Page directive contains an attribute that identifies this WebForm1 class.

Visual Studio has created all the initialization code necessary to display the calendar and provide it with default behavior.

To flesh out this example, add the missing controls and then wire up the event handlers. Return to the Design form and add the controls in Table 6-9 to the form.

Table 6-9. Label controls

ID

Type

(ASP control unless noted otherwise)

Text

Location

lblMonthChanged

Label

Above the calendar control

lblCount

Label

Immediately below the Calendar control

lblTodaysDate

Label

Immediately below lblCount

lblSelected

Label

Immediately below lblTodaysDate

HTML Label

Select a month

Below lblSelected

ddl

DropDownList

To the right of label

btnTGIF

Button

TGIF

To the right of ddl

HTML Label

Date Range

Below month label

HTML Label

Start Date

Below Date Range label

HTML Label

End Date

To right of Start Date label

txtStart

TextBox

Below Start Date label

txtEnd

TextBox

Below End Date label

btnRange

Button

Apply

To right of txtEnd

Be sure to set the Text property of each of the Labels as indicated in Table 6-9. If the label is an ASP control (from the Web Forms tab of the Toolbox), then the Text property is set in the Properties window. On the other hand, if the label is an HTML Label control (from the HTML tab of the Toolbox), the text is entered directly on the control, not in the Properties window (which identifies the type of control as DIV).

When adding the DropDownList control, set the AutoPostBack property to True. Also, you need to add all the ListItems. Click on the Items property and a build button (...) appears. Click on that and a ListItem Collection Editor dialog box pops up, as shown in Figure 6-12.

ListItem Collection Editor dialog box

Figure 6-12. ListItem Collection Editor dialog box

Click the Add button to add each of the months of the year, along with a value. The values to use are 1 through 12, corresponding to the number of the month.

All the other controls are very straightforward. Be sure to use the correct ID so that the event handlers you are going to copy in will work.

Once all the controls are added to the page, open the code-behind file. You should see that there are protected member variables for each of the controls you’ve added to the form.

In order to make this web page fully functional, however, thePage_Load method needs to be coded and all the relevant controls need to have event handlers. Specifically, the calendar needs to respond to selecting a different day, to rendering each of the cells containing a day, and to changing the month. Also, the drop-down list needs to respond to a month being selected, and the two buttons need to respond to clicks. Copy the necessary code from Example 5-49 in C#, and Example 5-50 in VB.NET, that provided these event handlers.

Before creating any of the event handlers, copy the private helper methods shown in Example 6-17 (C#) and Example 6-18 (VB.NET) -- taken from Example 5-49 and Example 5-50, respectively -- to the code-behind page.

Example 6-17. C# helper methods

private void lblCountUpdate(  )
{
   lblCount.Text = "Count of Days Selected:  " + 
         cal.SelectedDates.Count.ToString(  );
}

private void lblSelectedUpdate(  )
{
   if (cal.SelectedDate != DateTime.MinValue)
      lblSelected.Text = "The date selected is " + 
            cal.SelectedDate.ToShortDateString(  );
   else
     lblSelected.Text = "";
}

private void txtClear(  )
{
   txtStart.Text = "";
   txtEnd.Text = "";
}

Example 6-18. VB.NET helper methods

private sub lblCountUpdate(  )
   lblCount.Text = "Count of Days Selected:  " & _
         cal.SelectedDates.Count.ToString(  )
end sub

private sub lblSelectedUpdate(  )
   if (cal.SelectedDate <> DateTime.MinValue) then
      lblSelected.Text = "The date selected is " & _
            cal.SelectedDate.ToShortDateString(  )
   else
     lblSelected.Text = ""
   end if
end sub

private sub txtClear(  )
   txtStart.Text = ""
   txtEnd.Text = ""
end sub

Next, copy the contents of the Page_Load method from Example 5-49 (C#) and Example 5-50 (VB.NET) to the code-behind page. Notice that the code-behind page already has a shell of the Page_Load method. You should copy only the code within the shell. When completed, the Page_Load method should look like Example 6-19 in C# and Example 6-20 in VB.NET.

Example 6-19. Page_Load in C#

private void Page_Load(object sender, System.EventArgs e)
{
   // Put user code to initialize the page here
   if (!IsPostBack)
   {
      cal.VisibleDate = cal.TodaysDate;
      ddl.SelectedIndex = cal.VisibleDate.Month - 1;
   }
   lblTodaysDate.Text = "Today's Date is " +  
         cal.TodaysDate.ToShortDateString(  );
}

Example 6-20. Page_Load in VB.NET

Private Sub Page_Load(ByVal sender As System.Object, _
                      ByVal e As System.EventArgs) Handles MyBase.Load
    'Put user code to initialize the page here
     if not IsPostBack then
        cal.VisibleDate = cal.TodaysDate
        ddl.SelectedIndex = cal.VisibleDate.Month - 1
     end if

     lblTodaysDate.Text = "Today's Date is " & _
           cal.TodaysDate.ToShortDateString(  )
End Sub

Now it is time to hook up the event handlers. Double-click on the calendar control in the Design view. This creates an event handler for the SelectionChanged event in the code-behind page and places the cursor inside the shell for that event handler method. Then copy the code for the SelectionChanged event handler method from Example 5-49 (C#) and Example 5-50 (VB.NET) to inside the method shell created in the code-behind page. When you are finished, the cal_SelectionChanged method should look like Example 6-21 in C# and Example 6-22 in VB.NET.

Example 6-21. cal_SelectionChanged method in C#

private void cal_SelectionChanged(object sender, System.EventArgs e)
{
   lblSelectedUpdate(  );
   lblCountUpdate(  );
   txtClear(  );
}

Example 6-22. cal_SelectionChanged method in VB.NET

Private Sub cal_SelectionChanged(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) _
                                Handles cal.SelectionChanged
   lblSelectedUpdate(  )
   lblCountUpdate(  )
   txtClear(  )
End Sub

You also need to hook up two other events for the calendar control: DayRender and VisibleMonthChanged. This is done differently in C# and VB.NET.

To hook up the events in C#, click on the Calendar control in the Design window, then click on the Events icon (pictured previously in Section 6.5.1) in the toolbar at the top of the Properties box. All the possible events for the Calendar control are listed. Click on the DayRender event. Type in the name of the event handler method to use. In this example, type in cal_DayRender. Then go to the code-behind page. You will see that a shell has been created for that method. Copy in the contents of the DayRender method from Example 5-49. (Notice that you are using slightly different method names here than were used in Example 5-49. The actual names are not important, as long as they are consistent within each example.)

Do the same thing for the VisibleMonthChanged event, entering the method name cal_VisibleMonthChanged. Again, copy the contents of the VisibleMonthChanged method from Example 5-49.

When you are finished, the two methods in Visual Studio .NET should look like the code in Example 6-23.

Example 6-23. Calendar DayRender and VisibleMonthChanged methods in C#

private void cal_DayRender(object sender,
                System.Web.UI.WebControls.DayRenderEventArgs e)
{
   //  Notice that this overrides the WeekendDayStyle.
   if (!e.Day.IsOtherMonth && e.Day.IsWeekend)
      e.Cell.BackColor=System.Drawing.Color.LightGreen;

   //  Happy New Year!
   if (e.Day.Date.Month == 1 && e.Day.Date.Day == 1)
      e.Cell.Controls.Add(new LiteralControl("<br/>Happy New Year!"));
}

private void cal_VisibleMonthChanged(object sender,
              System.Web.UI.WebControls.MonthChangedEventArgs e)
{
   if (e.NewDate.Month > e.PreviousDate.Month)
      lblMonthChanged.Text = "My future's so bright...";
   else
      lblMonthChanged.Text = "Back to the future!";

   cal.SelectedDates.Clear(  );
   lblSelectedUpdate(  );
   lblCountUpdate(  );
   txtClear(  );
}

The remaining events are hooked up similarly. You can either double-click on each control, which automatically creates the event handler method shell in the code-behind page, or use the Events icon from the Properties window for each control. In either case, you need to add the methods for the controls listed in Table 6-10. For each event handler, copy the code from the corresponding event handler method in Example 5-49. When you are done, the event handler methods should like the code in Example 6-24.

Table 6-10. Controls and methods for Example 6-24 (C#)

Control

Event handler method

ddl

ddl_SelectedIndexChanged

btnTGIF

btnTGIF_Click

btnRange

btnRange_Click

Example 6-24. Remaining event handling methods in C#

private void ddl_SelectedIndexChanged(object sender, System.EventArgs e)
{
   cal.SelectedDates.Clear(  );
   lblSelectedUpdate(  );
   lblCountUpdate(  );
   txtClear(  );
   cal.VisibleDate = new DateTime(cal.TodaysDate.Year, 
                     Int32.Parse(ddl.SelectedItem.Value), 1);
}

private void btnTGIF_Click(object sender, System.EventArgs e)
{
   int currentMonth = cal.VisibleDate.Month;
   int currentYear = cal.VisibleDate.Year;

   cal.SelectedDates.Clear(  );

   for (int i = 1; 
            i <= System.DateTime.DaysInMonth(currentYear, 
                                             currentMonth); 
            i++ )
   {
      DateTime date = new DateTime(currentYear, currentMonth, i);
      if (date.DayOfWeek == DayOfWeek.Friday)
         cal.SelectedDates.Add(date);
   }

   lblSelectedUpdate(  );
   lblCountUpdate(  );
   txtClear(  );
}

private void btnRange_Click(object sender, System.EventArgs e)
{
   int currentMonth = cal.VisibleDate.Month;
   int currentYear = cal.VisibleDate.Year;
   DateTime StartDate = new DateTime(currentYear, currentMonth, 
                        Int32.Parse(txtStart.Text));
   DateTime EndDate = new DateTime(currentYear, currentMonth, 
                     Int32.Parse(txtEnd.Text));

   cal.SelectedDates.Clear(  );
   cal.SelectedDates.SelectRange(StartDate, EndDate);

   lblSelectedUpdate(  );
   lblCountUpdate(  );
}

The procedure to hook up the remaining events in VB.NET is different than in C# because Visual Studio .NET does not have an Events icon for VB.NET. Instead, you follow these steps:

  1. Move to the code-behind page by clicking on the WebForm1.aspx.vb tab.

  2. Click on the drop-down at the top left of the code page to see a list of all the controls on the page.

  3. Select the control to which you want to add an event handler.

  4. Click on the drop-down at the top right of the code page. This will list all the possible events for that control.

  5. Select the desired event. A code shell will be created in the code page, ready to accept the code to handle the event.

  6. Copy the code for the event handler method from Example 5-50 to the code page.

Perform these steps for each of the controls and event handler methods listed in Table 6-11. When you are finished, the code for all these methods should look like Example 6-25.

Table 6-11. Controls and methods for Example 6-25 (VB.NET)

Control

Event handler method

cal

cal_DayRender

cal

cal_VisibleMonthChanged

ddl

ddl_SelectedIndexChanged

btnTGIF

btnTGIF_Click

btnRange

btnRange_Click

Example 6-25. Remaining event handling methods in VB.NET

Private Sub cal_DayRender(ByVal sender As Object, _
            ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) _
            Handles cal.DayRender
   '  Notice that this overrides the WeekendDayStyle.
   if (not e.Day.IsOtherMonth and e.Day.IsWeekend) then
      e.Cell.BackColor=System.Drawing.Color.LightGreen
   end if

   '  Happy New Year!
   if (e.Day.Date.Month = 1 and e.Day.Date.Day = 1) then
      e.Cell.Controls.Add(new LiteralControl("<br/>Happy New Year!"))
   end if
End Sub

Private Sub cal_VisibleMonthChanged(ByVal sender As Object, _
        ByVal e As System.Web.UI.WebControls.MonthChangedEventArgs) _
        Handles cal.VisibleMonthChanged
   if (e.NewDate.Month > e.PreviousDate.Month) then
      lblMonthChanged.Text = "My future's so bright..."
   else
      lblMonthChanged.Text = "Back to the future!"
   end if


   cal.SelectedDates.Clear(  )
   lblSelectedUpdate(  )
   lblCountUpdate(  )
   txtClear(  )
End Sub

Private Sub ddl_SelectedIndexChanged(ByVal sender As Object, _
           ByVal e As System.EventArgs) _
           Handles ddl.SelectedIndexChanged
   cal.SelectedDates.Clear(  )
   lblSelectedUpdate(  )
   lblCountUpdate(  )
   txtClear(  )
   cal.VisibleDate = new DateTime(cal.TodaysDate.Year, _
                     Int32.Parse(ddl.SelectedItem.Value), 1)
End Sub

Private Sub btnTGIF_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs) _
            Handles btnTGIF.Click
   dim currentMonth as integer = cal.VisibleDate.Month
   dim currentYear as integer = cal.VisibleDate.Year

   cal.SelectedDates.Clear(  )

   dim i as integer
   for i = 1 to System.DateTime.DaysInMonth(currentYear, _
                                            currentMonth)
      dim dt as DateTime = new DateTime(currentYear, _
                                        currentMonth, _
                                        i)
      if dt.DayOfWeek = DayOfWeek.Friday then
         cal.SelectedDates.Add(dt)
      end if
   next

   lblSelectedUpdate(  )
   lblCountUpdate(  )
   txtClear(  )
End Sub

Private Sub btnRange_Click(ByVal sender As Object, _
              ByVal e As System.EventArgs) _
              Handles btnRange.Click
   dim currentMonth as integer = cal.VisibleDate.Month
   dim currentYear as integer = cal.VisibleDate.Year
   dim StartDate as DateTime = new DateTime(currentYear, _
                                            currentMonth, _
                                            Int32.Parse(txtStart.Text))
   dim EndDate as DateTime = new DateTime(currentYear, _
                                          currentMonth, _
                                          Int32.Parse(txtEnd.Text))
   cal.SelectedDates.Clear(  )
   cal.SelectedDates.SelectRange(StartDate, EndDate)

   lblCountUpdate(  )
End Sub

Visual Studio .NET automatically inserts some additional code to enable the event handlers to be properly hooked up with the controls. This code differs in C# and VB.NET.

In the C# code-behind page, there is a method called InitializeComponent, shown here in Example 6-26.

Example 6-26. Event handler hookup in C# code-behind file

private void InitializeComponent(  )
{    
   this.btnTGIF.Click += 
              new System.EventHandler(this.btnTGIF_Click);
   this.cal.DayRender += 
              new System.Web.UI.WebControls.DayRenderEventHandler(
                   this.cal_DayRender);
   this.cal.VisibleMonthChanged += 
              new System.Web.UI.WebControls.MonthChangedEventHandler(
                   this.cal_VisibleMonthChanged);
   this.cal.SelectionChanged += 
              new System.EventHandler(this.cal_SelectionChanged);
   this.ddl.SelectedIndexChanged += 
              new System.EventHandler(this.ddl_SelectedIndexChanged);
   this.btnRange.Click += new System.EventHandler(this.btnRange_Click);
   this.Load += new System.EventHandler(this.Page_Load);
}

For VB.NET, the equivalent code is found near the top of the class declaration, as shown in Example 6-27.

Example 6-27. Event handler hookups in VB.NET code-behind

Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents lblMonthChanged As System.Web.UI.WebControls.Label
Protected WithEvents lblCount As System.Web.UI.WebControls.Label
Protected WithEvents lblTodaysDate As System.Web.UI.WebControls.Label
Protected WithEvents lblSelected As System.Web.UI.WebControls.Label
Protected WithEvents ddl As System.Web.UI.WebControls.DropDownList
Protected WithEvents btnTGIF As System.Web.UI.WebControls.Button
Protected WithEvents txtStart As System.Web.UI.WebControls.TextBox
Protected WithEvents txtEnd As System.Web.UI.WebControls.TextBox
Protected WithEvents btnRange As System.Web.UI.WebControls.Button
Protected WithEvents cal As System.Web.UI.WebControls.Calendar

Run the form (F5) and verify that everything works. Be sure to save everything either by clicking on the Save All icon on the toolbar or clicking on File/All from the VS.NET menu.

Close VS.NET and run your new form by opening a browser and entering the following URL:

http://localhost/FirstWebApp/WebForm1.aspx

You should then see something like Figure 6-13.

Completed calendar web page

Figure 6-13. Completed calendar web page

If you compare the operation of the hand-coded web page shown in Figure 6-13 with that created in VS.NET, you’ll notice one small difference. When the hand-coded page first appears in the browser, before you click on anything, the space between the month DropDownList and the Calendar control is closed up. Although there are three Label controls there, they are empty and do not take up any space. In the VS.NET created page, however, those labels take up space, even when empty.

This is caused by a fundamental difference in the way the two pages are laid out. The hand-coded page uses no absolute positioning but rather strategically placed break (<br/>) and paragraph (<p/>) tags, as well as an HTML table. In the VS.NET-produced page, all the controls have a style attribute that includes positioning information.

If you want the page layout in the Designer to not use absolute positioning but rather to use paragraph tags (<p>) as in the hand-coded version, then change the pageLayout property of the Document in Design mode from GridLayout (the default) to FlowLayout .

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.203.96