Calendar Control and Data Sources

Chapter 5 - Reading Data using the Dataset Object
byJohn Kauffman, Fabio Claudio Ferracchiatiet al.?
Wrox Press ?2002

Many software designers are working on ASP.NET controls, just as they supplied controls for classic ASP. As a demonstration of what can be done with the .NET architecture, Microsoft has developed the Calendar web server control, and included it with ASP.NET - it can be used to display a one-month calendar that allows the user to select dates, and to 'move' to the next and previous months. In this section, we're going to focus on how to get dates from a data source and display them in the control.

When dealing with the Calendar control, there are three main points to understand. First, the control shows the current month by default, but the VisibleDate property can be used to change this - you can use it to specify any day you like.

Second, we have a choice of four settings for the SelectionMode property that will determine how many days can be selected at once. The options are the four members of the CalendarSelectionMode enumeration: Day (a single day can be selected), DayWeek (a single day or an entire week can be selected), DayWeekMonth, and None (no selection allowed). Day mode returns a single date that resides in the SelectedDate property; if multiple items are selected, they are put in a collection named SelectedDates.

Third, dates from certain data sources - including some forms of dates from a Microsoft Access database - will not have formats that are valid for the Calendar control. For example, if you want to use a field that was established in Access as a date/time type in dd-mmm-yyyy format, that value will be stored in a DataSet object in a form that the Calendar control does not recognize. We need to convert that value using a .NET class called Convert; this includes a ToDateTime() method that takes account of the server's localization settings for date formatting.

    Convert.ToDateTime(MyDataSet.Tables("MyTable").Rows(MyIndex)("MyDateField")) 

With these tips, our knowledge of how to work with DataSet objects, and our experience of reading specific values from a DataSet, we're ready to use the Calendar control as a front end to our data.

Try It Out - The Calendar Web Server Control

start example

In this example, we'll create two pages. The first will be a warm-up - we'll just show the date selected from a Calendar control in a label. In the second version, we'll add a list box of employees, and arrange things so that when the user selects an employee, a Calendar will show the day and month when that employee was hired. In other words, we'll read data from Northwind and display it in a Calendar control.

  1. Create a new page named Calendar_1. aspx in the ch05 folder, and enter the following code:

     <%@ Import namespace="System.Data" %> <%@ Import namespace="System.Data.SqlClient" %> <html>   <head><title>Using the Calendar</title></head>   <body>     <h3>Using the Calendar</h3>     <form runat="server">       <asp:Label  runat="server" />       <asp:Calendar  runat="Server"                     SelectionMode = "DayWeek"                     OnSelectionChanged = "CalendarChange" />     </form>   </body> </html> <script language="VB" runat="server"> Sub CalendarChange(Source As Object, E As EventArgs)   lblSelectedDate.Text = calHire.SelectedDate End Sub </script> 

  2. Take a look at the page and select a few dates. Also try moving to another month. You should see something like the image below:

    click to expand

  3. For our next version, we'll connect to a data store. Re-save the file as Calendar_2 . aspx, and add the highlighted code, as follows:

     <%@ Import namespace="System.Data" %> <%@ Import namespace="System.Data.SqlClient" %> <html>   <head><title>Calendar: Hire Dates</title></head>   <body>     <h3>Calendar: Hire Dates</h3>     <form runat="server">       <asp:ListBox  runat="server"                    Rows="7"                    Autopostback="True" /><br/>       <asp:Label  runat="server" />       <asp:Calendar  runat="server"                     SelectionMode = "None" /> </form>   </body> </html> <script language="VB" runat="server"> Sub Page_Load(Source As Object, E As EventArgs)   Dim strConnection As String = ConfigurationSettings.AppSettings("NWind")   Dim objConnection As New SqlConnection(strConnection)   Dim strSQL As String = "SELECT EmployeeID, LastName, FirstName, HireDate " & _                          "FROM Employees;"   Dim objAdapter As New SqlDataAdapter(strSQL, objConnection)   Dim objDataSet As New DataSet("dsEmployees")   objAdapter.Fill(objDataSet, "dtEmployees")   If Not IsPostBack Then     lstEmployees.DataSource = objDataSet     lstEmployees.DataTextField = "LastName"     lstEmployees.DataBind()   Else     Dim datHireDate As Date     datHireDate = Convert.ToDateTime( _   objDataSet.Tables("dtEmployees").Rows(1stEmployees.SelectedIndex)("HireDate"))     lblSelectedDate.Text = _ objDataSet.Tables("dtEmployees").Rows(1stEmployees.SelectedIndex)("LastName")     calHire.VisibleDate = datHireDate     calHire.SelectedDate = datHireDate     lblSelectedDate.Text &= " hired on " & datHireDate   End If End Sub </script> 

  4. Now, when we run the above code, we see the following screen:

    click to expand

end example

How It Works

As is our habit, let's begin with a quick look at the body of the HTML in the page. We have an ASP.NET web server ListBox control, a label, and a Calendar control with id= "calHire".

        <form runat="server">          <asp:ListBox  runat="server"                       Rows="7"                       Autopostback="True" /><br/>          <asp:Label  runat="server" />          <asp:Calendar  runat="server"                        SelectionMode = "None" />        </form> 

In the Page_Load() event handler, we begin by creating our connection and retrieving information about the employees (including their hire date) from the Employees table. We then fill a DataTable object called dtEmployees with this data.

The interesting code begins when we check to see if this the first time we are loading the page. If it is, we bind objDataSet to our list box to display the employees.

       If Not IsPostBack Then         lstEmployees. DataSource = objDataSet         1stEmployees. DataTextField = "LastName"         lstEmployees.DataBind() 

If we're posting back to the page, then we wish to find the employee that has been selected from the list box, change the Calendar control to indicate their hire date, and change the Text of the label to display the hire date as well. The employee we have chosen is obtained from the SelectedIndex property of lstEmployees; this value will also indicate the DataRow of dtEmployees we need to access to obtain the HireDate and LastName. To ensure we have a correctly formatted date, we use Convert.ToDateTime():

      Else        Dim datHireDate As Date        datHireDate = Convert.ToDateTime( _    objDataSet.Tables("dtEmployees").Rows(1stEmployees.SelectedIndex)("HireDate"))        lblSelectedDate. Text = _    objDataSet.Tables("dtEmployees").Rows(lstEmployees.SelectedIndex)("LastName") 

Finally, we update the Calendar control to display the hire date, and display the last name of the employee and their hire date in the label:

        calHire.VisibleDate = datHireDate        calHire.SelectedDate = datHireDate        lblSelectedDate.Text &= " hired on " & datHireDate      End If 

In where we look at creating and inserting data, we'll see how to use the value in calHire. SelectedDate to update our data source.



Beginning ASP. NET 2.0 and Databases
Beginning ASP.NET 2.0 and Databases (Wrox Beginning Guides)
ISBN: 0471781347
EAN: 2147483647
Year: 2004
Pages: 263

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