Lab: Building the Contact Management Application

Lab: Building the Contact Management Application

In this lab, you ll create a multipage Web application that uses a database to store contact and call information. The application lets you add contacts, view and add calls made by a contact, and add new contact types. This application uses the Contacts SQL database installed by Setup on the companion CD.

The Contact Management application demonstrates these key concepts:

  • Navigation

    Users navigate from a central switchboard page to specific task pages. After users have finished a task, they navigate back to the switchboard page.

  • Central data connection

    The database connection, data adapter, and data set components reside in the Switchboard Web form. These objects are shared between Web forms using the application s Cache object.

  • Data set transactions

    All changes to the database are processed through data sets, and all updates are contained within error-handling structures. If an update fails, the user can try again or cancel the operation without damaging the integrity of the database.

  • Bound and unbound controls

    Calls are displayed using a DataList control containing data-bound label controls. Contacts are displayed in a DropDownList control using code rather than data binding.

Estimated lesson time: 60 minutes

Exercise 1: Start a Project and Create the SwitchBoard Form

In this exercise, you start a new project and create the Web form used to navigate to the other Web forms in the application.

When you have finished creating the SwitchBoard form, it will appear as shown in Figure 5-23.

figure 5-23 the switchboard form

Figure 5-23. The SwitchBoard form

To start the new application and create the SwitchBoard Web form

  1. Create a new ASP.NET Web application project named ContactManagement.

  2. Change the name of the Webform1.aspx file to SwitchBoard.aspx, and display the Web form in HTML mode.

  3. Type the following HTML between the <form> and </form> tags:

    <h2>Contact Management Switchboard</h2> <P>What would you like to do? </P> <P><a href="Calls.aspx">View/add calls.</a></P> <P><a href="AddContact.aspx">Add a contact.</a></P> <P><a href="DeleteContact.aspx">Delete a contact.</a></P> <P><a href="ContactTypes.aspx">Add a contact type.</a></P>

Exercise 2: Add Database Components

The Contact Management application performs data access from several different Web forms. The database connection, adapter, and data set components are added to the SwitchBoard Web form and saved as Cache variables so that they can be accessed from the other Web forms.

All the Web forms, and all users of the application, share a single database connection. This improves performance and makes it easier to maintain connection and adapter settings while developing the application because the database components are all located in one place: the SwitchBoard.aspx file.

To add the database components for the Contact Management application

  1. Open the SwitchBoard Web form in the Design window and click the Server Explorer link. Visual Studio displays the Server Explorer.

  2. Click the Connect To A Database button in the Server Explorer window. Visual Studio displays the Data Link Properties dialog box.

  3. Select the name of the SQL server where the Contacts sample database is installed, choose the Use Windows NT integrated security option, and then type Contacts in the Select The Database On The Server box. Click Test Connection to verify your settings, and then click OK when you have finished. Visual Studio adds the database connection to the Server Explorer.

  4. In the Server Explorer window, expand the items under the data connection you created by clicking the plus signs to the left of the Contacts.dbo data connection, and then do the same to the Tables subitem. Drag the Calls, ContactTypes, and Contacts tables from the Server Explorer to the SwitchBoard Web form. Visual Studio adds a database connection component and data adapter components for each of the tables.

  5. Each data adapter represents one of the tables you dragged onto the page. Right-click one of the data adapters and select Generate Data Set from the shortcut menu. Visual Studio displays the Generate DataSet dialog box.

  6. Type the name of the data set to create in the New text box. Name the data set after the table it represents (for example, dsCalls for the Calls table), and then select the Add This Dataset To The Designer check box and click OK. Visual Studio adds the data set to the SwitchBoard Web form.

    NOTE
    When Visual Studio adds a data set, it appends a number to the name you provide.

  7. Repeat steps 5 and 6 for each of the data adapters.

  8. Double-click the SwitchBoard Web form in the Design window to display the code for the page. Add the following Page_Load event procedure to create the Cache variables that you ll use from subsequent Web forms to access the database components:

    Visual Basic .NET

    Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' The first time this page is displayed... If Not IsPostBack Then AddToCache("adptCalls", SqlDataAdapter1) AddToCache("adptContactTypes", SqlDataAdapter2) AddToCache("adptContacts", SqlDataAdapter3) ' Fill data sets and add them to Cache. SqlDataAdapter1.Fill(DsCalls1) AddToCache("dsCalls", DsCalls1) SqlDataAdapter2.Fill(DsContactTypes1) AddToCache("dsContactTypes", DsContactTypes1) SqlDataAdapter3.Fill(DsContacts1) AddToCache("dsContacts", DsContacts1) End If End Sub Sub AddToCache(ByVal Name As String, ByVal Item As Object) ' If item is already in cache, simply return. If Not IsNothing(Cache(Name)) Then Return ' Otherwise, cache the item for 20 minutes with sliding expiration. Cache.Add(Name, Item, Nothing, DateTime.MaxValue, _ System.TimeSpan.FromMinutes(20), _ Caching.CacheItemPriority.Default, Nothing) End Sub

    Visual C#

    private void Page_Load(object sender, System.EventArgs e) { // The first time this page is displayed... if (!IsPostBack) { AddToCache("adptCalls", sqlDataAdapter1); AddToCache("adptContactTypes", sqlDataAdapter2); AddToCache("adptContacts", sqlDataAdapter3); // Fill data sets and add them to Cache. sqlDataAdapter1.Fill(dsCalls1); AddToCache("dsCalls", dsCalls1); sqlDataAdapter2.Fill(dsContactTypes1); AddToCache("dsContactTypes", dsContactTypes1); sqlDataAdapter3.Fill(dsContacts1); AddToCache("dsContacts", dsContacts1); } } void AddToCache(string Name, object Item) { // If item is already in cache, simply return. if (Cache[Name] != null) return; // Otherwise, cache the item for 20 minutes with sliding expiration. Cache.Add(Name, Item, null, DateTime.MaxValue, System.TimeSpan.FromMinutes(20), System.Web.Caching.CacheItemPriority.Default, null); }

The preceding code adds the database connection, adapters, and data sets to the application s cached data. The Cache object is just like the Application state object; however, Cache allows you to set expiration rules for the data. The AddToCache procedure checks whether the items are already cached (perhaps because another session started the application previously) and adds the items if they are not found. If the cached item is not accessed for more than 20 minutes, it is unloaded from memory.

Exercise 3: Create the AddContact Form

The Contact Management application allows users to add information about new contacts through the AddContact Web form. The AddContact Web form is a straightforward data entry form with text boxes for each of the data items in a Contacts table record. When complete, the AddContact Web form will appear as shown in Figure 5-24.

figure 5-24 the addcontact web form

Figure 5-24. The AddContact Web form

To create the AddContact data entry Web form

  1. Add a new Web form to the project named AddContact.aspx.

  2. In the Properties window, select the DOCUMENT object and set the pageLayout property to FlowLayout.

  3. Add controls to the Web form with the property settings shown in the following table:

    Control

    Property

    Setting

    TextBox

    ID

    txtFirstName

    TextBox

    ID

    txtLastName

    TextBox

    ID

    txtAddress

    TextMode

    MultiLine

    TextBox

    ID

    txtCity

    DropDownList

    ID

    drpStates

    DataSource

    arrState

    TextBox

    ID

    txtZIP

    TextBox

    ID

    txtHomePhone

    TextBox

    ID

    txtWorkPhone

    TextBox

    ID

    txtNotes

    DropDownList

    ID

    drpContactTypes

    DataSource

    dsContactTypes

    DataTextField

    ContactType

    DataValueField

    ContactTypeID

    Button

    ID

    butAdd

    Text

    Add

    Button

    ID

    butCancel

    Text

    Cancel

    Literal

    ID

    litStatus

    Hyperlink

    Text

    Return to SwitchBoard

    NavigateUrl

    SwitchBoard.aspx

  4. Type text to identify the fields directly on the Web form. Use carriage returns to start new lines.

  5. Double-click the Web form to display the Code window, and then add the following Imports or using statement to the top of the module:

    Visual Basic .NET

    Imports System.Data.SqlClient

    Visual C#

    using System.Data.SqlClient;

  6. The AddContact Web form uses the database components created in Exercise 2 in the SwitchBoard Web form. To use these components in this Web form, declare class-level variables, and then retrieve the references to the components from the state variables where they are stored. The following code demonstrates how to do this:

    Visual Basic .NET

    Dim adptContacts As SqlDataAdapter Dim dsContacts As dsContacts ' These variables are public for data binding. Public dsContactTypes As dsContactTypes Public arrState As String() = {"AL", "AK", "AR", "AZ", _  "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", _  "IN", "IA", "KS", "KY", "LA", "MA", "ME", "MD", "MI", _  "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", _  "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "SC", _  "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WY"} Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Get the Cached variables. adptContacts = Cache("adptContacts") dsContacts = Cache("dsContacts") dsContactTypes = Cache("dsContactTypes") If Not IsPostBack Then ' Bind to data -- populates the drpContactTypes and drpState lists. drpContactTypes.DataBind() drpStates.DataBind() End If End Sub

    Visual C#

    SqlDataAdapter adptContacts; MCSDWebAppsCS.Chapter05.dsContacts dsContacts; // These variables are public for data binding. public MCSDWebAppsCS.Chapter05.dsContactTypes dsContactTypes; public string[] arrState = {"AL", "AK", "AR", "AZ",  "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL",  "IN", "IA", "KS", "KY", "LA", "MA", "ME", "MD", "MI",  "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ",  "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "SC",  "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WY"}; private void Page_Load(object sender, System.EventArgs e) { // Get the Cached variables. adptContacts = (SqlDataAdapter) Cache["adptContacts"]; dsContacts = (dsContacts) Cache["dsContacts"]; dsContactTypes = (dsContactTypes) Cache["dsContactTypes"]; if (!IsPostBack) { // Bind to data -- populates drpContactTypes and drpState lists. drpContactTypes.DataBind(); drpStates.DataBind(); } }

  7. Each contact in the Contacts table is identified by a ContactID. This is the primary key for the table, so it must be unique for each contact. Therefore, before you can add a contact to the Contacts data set, you must obtain a new, unique ContactID from the database. Add the following helper function to the Web form class to get this unique ID before adding the contact:

    Visual Basic .NET

    ' Helper function to get a new, valid row ID. Function GetNewID(ByVal dt As DataTable) As Integer ' Get a new row number. Dim NextID As Integer = dt.Rows.Count + 1 ' If it isn't found in the table, return it. If IsNothing(dt.Rows.Find(NextID)) Then Return NextID ' Otherwise, check for free IDs between 1 and the row count. For NextID = 1 To dt.Rows.Count ' Check if this ID already exists. If IsNothing(dt.Rows.Find(NextID)) Then Return NextID End If Next ' Failed, return zero. Return 0 End Function

    Visual C#

    // Helper function to get a new, valid row ID. int GetNewID(DataTable dt) { // Get a new row number. int NextID = dt.Rows.Count + 1; // If it isn't found in the table, return it. if (dt.Rows.Find(NextID) == null) return NextID; // Otherwise, check for free IDs between 1 and the row count. for(NextID = 1; NextID <= dt.Rows.Count; NextID++) { // Check if this ID already exists. if (dt.Rows.Find(NextID) == null) return NextID; } // Failed, return zero. return 0; }

  8. Add the following butAdd_Click event procedure to add the new contact information to the database:

    Visual Basic .NET

    Private Sub butAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butAdd.Click ' Create a new row for the data set. Dim rowNew As dsContacts.ContactsRow rowNew = dsContacts.Contacts.NewContactsRow() ' Add data to the row. rowNew.ContactID = GetNewID(dsContacts.Tables("Contacts")) rowNew.FirstName = txtFirstName.Text rowNew.LastName = txtLastName.Text rowNew.Address = txtAddress.Text rowNew.City = txtCity.Text rowNew.StateOrProvince = drpStates.SelectedItem.Text rowNew.PostalCode = txtZip.Text rowNew.HomePhone = txtHomePhone.Text rowNew.WorkPhone = txtWorkPhone.Text rowNew.Notes = txtNotes.Text rowNew.ContactTypeID = drpContactTypes.SelectedItem.Value ' Add the row to the data set. dsContacts.Contacts.AddContactsRow(rowNew) 'dsContacts.Contacts.Rows(0).Table.Columns(0).ToString() Try ' Modify the database. adptContacts.Update(dsContacts) ' Show success. litStatus.Text = rowNew.FirstName & " " & rowNew.LastName & _  " added successfully.<br>" ' Clear fields. ClearTextBoxes() ' Occurs if ContactID is not unique. Catch ex As Exception litStatus.Text = "The following database error occurred:<br>" & _ ex.Message & "<br>" & _  "Correct the error and click Add to add the contact " & _  "or click Cancel to abort.<br>" End Try End Sub

    Visual C#

    private void butAdd_Click(object sender, System.EventArgs e) { // Create a new row for the data set. dsContacts.ContactsRow rowNew; rowNew = dsContacts.Contacts.NewContactsRow(); // Add data to the row. rowNew.ContactID = GetNewID(dsContacts.Tables["Contacts"]); rowNew.FirstName = txtFirstName.Text; rowNew.LastName = txtLastName.Text; rowNew.Address = txtAddress.Text; rowNew.City = txtCity.Text; rowNew.StateOrProvince = drpStates.SelectedItem.Text; rowNew.PostalCode = txtZip.Text; rowNew.HomePhone = txtHomePhone.Text; rowNew.WorkPhone = txtWorkPhone.Text; rowNew.Notes = txtNotes.Text; rowNew.ContactTypeID = Convert.ToInt16(drpContactTypes.SelectedItem.Value); // Add the row to the data set. dsContacts.Contacts.AddContactsRow(rowNew); try { // Modify the database. adptContacts.Update(dsContacts); // Show success. litStatus.Text = rowNew.FirstName + " " + rowNew.LastName +  " added successfully.<br>"; // Redisplay page to clear fields. ClearTextBoxes(); } // General data exception, so report it. catch(Exception) { litStatus.Text = "The following database error occurred:<br>" + ex.Message + "<br>" +  "Correct the error and click Add to add the contact " +  "or click Cancel to abort.<br>"; } }

  9. Add the butCancel_Click event procedure to allow the user to cancel the operation and clear the text boxes on the form:

    Visual Basic .NET

    Private Sub butCancel_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butCancel.C lick ' Clear text fields on this page. ClearTextBoxes() End Sub ' Helper function to clear all the text boxes on this page. Sub ClearTextBoxes() Dim ctrl As Control For Each ctrl In Page.Controls If TypeOf ctrl Is HtmlForm Then Dim subctrl As Control For Each subctrl In ctrl.Controls If TypeOf subctrl Is System.Web.UI.WebControls.TextBox _ Then CType(subctrl, TextBox).Text = "" Next End If Next End Sub

    Visual C#

    private void butCancel_Click(object sender, System.EventArgs e) { ClearTextBoxes(); } void ClearTextBoxes() { foreach(object ctrl in Page.Controls) { if (ctrl is System.Web.UI.HtmlControls.HtmlForm) { System.Web.UI.HtmlControls.HtmlForm form = (System.Web.UI.HtmlControls.HtmlForm)ctrl; foreach(object subctrl in form.Controls) { if (subctrl is System.Web.UI.WebControls.TextBox) { TextBox textctrl = (TextBox)subctrl; textctrl.Text = ""; } } } } }

Exercise 4: Create the Calls Form

The Calls Web form lets users enter and view telephone calls from a contact. It uses a DataList control to view the telephone calls for a contact selected in a DropDownList control and contains the controls that add a call in a Panel control so that they can be hidden and displayed when the user clicks Add.

When completed, the Calls Web form appears as shown in Figure 5-25.

figure 5-25 the calls form

Figure 5-25. The Calls form

To create the Calls Web form

  1. Add a new Web form to the project named Calls.aspx.

  2. Add controls to the Web form with the property settings shown in the following table. Place the controls shown after the Panel control inside the panel so that you can easily control their display at run time.

    Control

    Property

    Setting

    DropDownList

    ID

    drpContacts

    Button

    ID

    butView

    Text

    View Call

    Button

    ID

    butAddCall

    Text

    Add Call

    Panel

    ID

    pnlAdd

    TextBox

    ID

    txtDate

    TextBox

    ID

    txtTime

    TextBox

    ID

    txtSubject

    TextBox

    ID

    txtNotes

    TextMode

    Multiline

    Button

    ID

    butOKAdd

    Text

    OK

    Button

    ID

    butCancelAdd

    Text

    Cancel

    Literal

    ID

    litError

  3. Open the Data tab in the Toolbox, and drag a DataSet onto the Web form. Visual Studio displays the Add Dataset dialog box with the Typed Dataset option selected.

  4. In the Name drop-down list, select the typed data set named ContactManagement.dsCalls, and click OK. Visual Studio adds the data set to the Web form.

  5. From the Web Forms tab in the Toolbox, add a DataList control to the Web form below the panel. Set its properties and edit its templates as shown in the following table:

    Control

    Property

    Setting

    DataList

    ID

    dlstCalls

    DataSource

    dsCalls.Tables( Calls ).DefaultView (VB)

    dsCalls.Tables[ Calls ].DefaultView (C#)

    DataList Header Template

    Regular text

    None

    Calls

    HTML rule

    None

    <HR>

    DataList Footer Template

    HTML rule

    None

    <HR>

    DataList Item Template

    Label

    ID

    lblDate

    (DataBindings)

    Using the DataBindings dialog box, select the Text property, and enter this custom binding expression: DataBinder.Eval(Container, "DataItem.CallDate", "{0:d}").

    Label

    ID

    lblTime

    (DataBindings)

    Using the DataBindings dialog box, select the Text property and enter this custom binding expression: DataBinder.Eval(Container, "DataItem.CallTime", "{0:t}").

    Regular text

    None

    Subject:

    Label

    ID

    lblSubject

    (DataBindings)

    Using the DataBindings dialog box, select the Text property and enter the following custom binding expression: DataBinder.Eval(Container, DataItem.Subject ).

    Regular text

    None

    Notes:

    Label

    ID

    lblNotes

    (DataBindings)

    Using the DataBindings dialog box, select the Text property and enter the following custom binding expression: DataBinder.Eval(Container, DataItem.Notes ).

    Separator Template

    HTML rule

    None

    <HR>

  6. Copy the Hyperlink control from the bottom of the AddContact form to the bottom of the Calls form. To copy the control, select the control and press Ctrl+C. To paste the copy onto the Calls form, click the form in Design mode and press Ctrl+V.

  7. Double-click the Calls Web form to display the Code window, and add the following Imports or using statements to the top of the module:

    Visual Basic .NET

    Imports System.Data.SqlClient

    Visual C#

    using System.Data.SqlClient;

  8. The Calls Web form uses the data components from the cache, so you need to retrieve references to those components from the Cache variables created in Exercise 2. The following declarations and Page_Load event procedure retrieve references to the data components and make them available to the form code:

    Visual Basic .NET

     Dim adptCalls As SqlDataAdapter Dim dsCalls As dsCalls Dim dsContacts As dsContacts Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Get cached variables. adptCalls = Cache("adptCalls") dsCalls = Cache("dsCalls") dsContacts = Cache("dsContacts") ' Run the first time page is displayed. If Not IsPostBack Then ' For each row in the table... Dim rowNext As dsContacts.ContactsRow For Each rowNext In dsContacts.Contacts ' Create a new list item. Dim lstNew As New ListItem() lstNew.Text = rowNext.FirstName & " " & rowNext.LastName lstNew.Value = rowNext.ContactID ' Add the list item to the drop-down list. drpContacts.Items.Add(lstNew) Next ' Select the first item in the list. drpContacts.SelectedIndex = 0 End If End Sub

    Visual C#

    SqlDataAdapter adptCalls; dsContacts dsContacts; public dsCalls dsCalls; private void Page_Load(object sender, System.EventArgs e) { // Get cached variables. adptCalls = (SqlDataAdapter) Cache["adptCalls"]; dsCalls = (dsCalls)Cache["dsCalls"]; dsContacts = (dsContacts)Cache["dsContacts"]; // Run the first time page is displayed. if (!IsPostBack) { // For each row in the table... foreach (dsContacts.ContactsRow rowNext in dsContacts.Contacts) { // Create a new list item. ListItem lstNew = new ListItem(); lstNew.Text = rowNext.FirstName + " " + rowNext.LastName; lstNew.Value = rowNext.ContactID.ToString(); // Add the list item to the drop-down list. drpContacts.Items.Add(lstNew); } // Select the first item in the list. drpContacts.SelectedIndex = 0; }

  9. Add the following code for the View Call and Add Call button Click event procedures:

    Visual Basic .NET

    Private Sub butView_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butView.Click ' Set the filter for the view to display. dsCalls.Tables("Calls").DefaultView.RowFilter = "Contactcodeblock_unnumbered">

    Visual C#

    private void butView_Click(object sender, System.EventArgs e) { // Set the filter for the view to display. dsCalls.Tables["Calls"].DefaultView.RowFilter = "Contactnormal">Add the following helper function to get a new CallID value. Because CallID is the primary key in the Calls table, you need a value that is unique within the database. This code is the same as used in the AddContact Web form and can, alternatively, be placed in a class module of helper functions and used from there.

    Visual Basic .NET

    ' Helper function to get a new, valid row ID. Function GetNewID(ByVal dt As DataTable) As Integer ' Get a new row number. Dim NextID As Integer = dt.Rows.Count + 1 ' If it isn't found in the table, return it. If IsNothing(dt.Rows.Find(NextID)) Then Return NextID ' Otherwis, check for free IDs between 1 and the row count. For NextID = 1 To dt.Rows.Count ' Check if this ID already exists. If IsNothing(dt.Rows.Find(NextID)) Then Return NextID End If Next ' Failed, return zero. Return 0 End Function

    Visual C#

    // Helper function to get a new, valid row ID. int GetNewID(DataTable dt) { // Get a new row number. int NextID = dt.Rows.Count + 1; // If it isn't found in the table, return it. if (dt.Rows.Find(NextID) == null) return NextID; // Otherwis, check for free IDs between 1 and the row count. for(NextID = 1; NextID <= dt.Rows.Count; NextID++) { // Check if this ID already exists. if (dt.Rows.Find(NextID) == null) return NextID; } // Failed, return zero. return 0; }

  10. Add the following code to the OK and Cancel button event procedures. These event procedures are very similar to the ones used to add or cancel the adding of records in the Contacts table in Exercise 3.

    Visual Basic .NET

    Private Sub butOKAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butOKAdd.Click Dim rowNew As dsCalls.CallsRow rowNew = dsCalls.Calls.NewCallsRow rowNew.ContactID = drpContacts.SelectedItem.Value rowNew.CallID = GetNewID(dsCalls.Tables("Calls")) rowNew.CallDate = txtDate.Text rowNew.CallTime = txtDate.Text & " " + txtTime.Text rowNew.Subject = txtSubject.Text rowNew.Notes = txtNotes.Text ' Add row to calls data set. dsCalls.Calls.AddCallsRow(rowNew) Try adptCalls.Update(dsCalls) ' Hide the add call panel. pnlAdd.Visible = False ' Clear the fields. txtSubject.Text = "" txtNotes.Text = "" ' Enable the other controls. butView.Enabled = True butAddCall.Enabled = True drpContacts.Enabled = True Catch ex As Exception ' Display error. litError.Text = "The following error occurred while adding " + _  "the call:<br>" + ex.Message & "<br>" + _ "Correct the error and try again, "+_ "or click Cancel to abort.<br>" End Try End Sub Private Sub butCancelAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butCancelAdd.Click ' Hide the add call panel. pnlAdd.Visible = False ' Clear the fields. txtSubject.Text = "" txtNotes.Text = "" ' Enable the other controls. butAddCall.Enabled = True drpContacts.Enabled = True End Sub

    Visual C#

    private void butOKAdd_Click(object sender, System.EventArgs e) { MCSDWebAppsCS.Chapter05.dsCalls.CallsRow rowNew; rowNew = dsCalls.Calls.NewCallsRow(); rowNew.ContactID = Convert.ToInt16(drpContacts.SelectedItem.Value); rowNew.CallID = GetNewID(dsCalls.Calls); rowNew.CallDate = Convert.ToDateTime(txtDate.Text); rowNew.CallTime = Convert.ToDateTime(txtTime.Text); rowNew.Subject = txtSubject.Text; rowNew.Notes = txtNotes.Text; // Add row to calls data set. dsCalls.Calls.AddCallsRow(rowNew); try { adptCalls.Update(dsCalls); // Hide the add call panel. pnlAdd.Visible = false; // Clear the fields. txtSubject.Text = ""; txtNotes.Text = ""; // Enable the other controls. butView.Enabled = true; butAddCall.Enabled = true; drpContacts.Enabled = true; } catch (Exception ex) { // Display error. litError.Text = "The following error occurred while adding " +  "the call:<br>" + ex.Message + "<br>" +  "Correct the error and try again, or click Cancel to " +  "abort.<br>"; } } private void butCancelAdd_Click(object sender, System.EventArgs e) { // Hide the add call panel. pnlAdd.Visible = false; // Clear the fields. txtSubject.Text = ""; txtNotes.Text = ""; // Enable the other controls. butAddCall.Enabled = true; drpContacts.Enabled = true; }

}

Exercise 5: Create the DeleteContact and ContactTypes Forms

So far, this lab has shown you how to create Web forms in a step-by-step fashion. Now it s time to strike out on your own! Create the DeleteContact and ContactTypes Web forms by yourself.

These Web forms should perform the following tasks:

  • Use the data components from the cache.

  • Perform operations on the database. The DeleteContact form should allow users to delete contacts from the database. The ContactTypes form should allow users to view and add new contact types.

  • Use data set transactions, as demonstrated by the AddContact and Calls forms.

  • Provide navigation back to the SwitchBoard form.

When you have finished, compare your results to the Contact Management sample included on the companion CD. Good luck!



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

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