"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Customizing the DataList’s Editing Interface (VB)

by Scott Mitchell

Download Sample App or Download PDF

In this tutorial we will create a richer editing interface for the DataList, one that includes DropDownLists and a CheckBox.

Introduction

The markup and Web controls in the DataList s EditItemTemplate define its editable interface. In all of the editable DataList examples we ve examined thus far, the editable interface has been composed of TextBox Web controls. In the preceding tutorial we improved the edit-time user experience by adding validation controls.

The EditItemTemplate can be further expanded to include Web controls other than the TextBox, such as DropDownLists, RadioButtonLists, Calendars, and so on. As with TextBoxes, when customizing the editing interface to include other Web controls, employ the following steps:

  1. Add the Web control to the EditItemTemplate.
  2. Use databinding syntax to assign the corresponding data field value to the appropriate property.
  3. In the UpdateCommand event handler, programmatically access the Web control value and pass it into the appropriate BLL method.

In this tutorial we will create a richer editing interface for the DataList, one that includes DropDownLists and a CheckBox. In particular, we’ll create a DataList that lists product information and permits the product s name, supplier, category, and discontinued status to be updated (see Figure 1).

The Editing Interface Includes a TextBox, Two DropDownLists, and a CheckBox

Figure 1: The Editing Interface Includes a TextBox, Two DropDownLists, and a CheckBox (Click to view full-size image)

Step 1: Displaying Product Information

Before we can create the DataList s editable interface, we first need to build the read-only interface. Start by opening the CustomizedUI.aspx page from the EditDeleteDataList folder and, from the Designer, add a DataList to the page, setting its ID property to Products. From the DataList s smart tag, create a new ObjectDataSource. Name this new ObjectDataSource ProductsDataSource and configure it to retrieve data from the ProductsBLL class s GetProducts method. As with the previous editable DataList tutorials, we’ll update the edited product s information by going directly to the Business Logic Layer. Accordingly, set the drop-down lists in the UPDATE, INSERT, and DELETE tabs to (None).

Set the UPDATE, INSERT, and DELETE Tabs Drop-Down Lists to (None)

Figure 2: Set the UPDATE, INSERT, and DELETE Tabs Drop-Down Lists to (None) (Click to view full-size image)

After configuring the ObjectDataSource, Visual Studio will create a default ItemTemplate for the DataList that lists the name and value for each of the data fields returned. Modify the ItemTemplate so that the template lists the product name in an <h4> element along with the category name, supplier name, price, and discontinued status. Moreover, add an Edit button, making sure that its CommandName property is set to Edit. The declarative markup for my ItemTemplate follows:

[!code-aspxMain]

   1:  <ItemTemplate>
   2:      <h4>
   3:          <asp:Label ID="ProductNameLabel" runat="server"
   4:              Text='<%# Eval("ProductName") %>' />
   5:      </h4>
   6:      <table border="0">
   7:          <tr>
   8:              <td class="ProductPropertyLabel">Category:</td>
   9:              <td class="ProductPropertyValue">
  10:                  <asp:Label ID="CategoryNameLabel" runat="server"
  11:                      Text='<%# Eval("CategoryName") %>' />
  12:              </td>
  13:              <td class="ProductPropertyLabel">Supplier:</td>
  14:              <td class="ProductPropertyValue">
  15:                  <asp:Label ID="SupplierNameLabel" runat="server"
  16:                      Text='<%# Eval("SupplierName") %>' />
  17:              </td>
  18:          </tr>
  19:          <tr>
  20:              <td class="ProductPropertyLabel">Discontinued:</td>
  21:              <td class="ProductPropertyValue">
  22:                  <asp:Label ID="DiscontinuedLabel" runat="server"
  23:                      Text='<%# Eval("Discontinued") %>' />
  24:              </td>
  25:              <td class="ProductPropertyLabel">Price:</td>
  26:              <td class="ProductPropertyValue">
  27:                  <asp:Label ID="UnitPriceLabel" runat="server"
  28:                      Text='<%# Eval("UnitPrice", "{0:C}") %>' />
  29:              </td>
  30:          </tr>
  31:          <tr>
  32:              <td colspan="4">
  33:                  <asp:Button runat="Server" ID="EditButton"
  34:                      Text="Edit" CommandName="Edit" />
  35:              </td>
  36:          </tr>
  37:      </table>
  38:      <br />
  39:  </ItemTemplate>

The above markup lays out the product information using an <h4> heading for the product s name and a four-column <table> for the remaining fields. The ProductPropertyLabel and ProductPropertyValue CSS classes, defined in Styles.css, have been discussed in previous tutorials. Figure 3 shows our progress when viewed through a browser.

The Name, Supplier, Category, Discontinued Status, and Price of Each Product is Displayed

Figure 3: The Name, Supplier, Category, Discontinued Status, and Price of Each Product is Displayed (Click to view full-size image)

Step 2: Adding the Web Controls to the Editing Interface

The first step in building the customized DataList editing interface is to add the needed Web controls to the EditItemTemplate. In particular, we need a DropDownList for the category, another for the supplier, and a CheckBox for the discontinued state. Since the product s price is not editable in this example, we can continue displaying it using a Label Web control.

To customize the editing interface, click on the Edit Templates link from the DataList s smart tag and choose the EditItemTemplate option from the drop-down list. Add a DropDownList to the EditItemTemplate and set its ID to Categories.

Add a DropDownList for the Categories

Figure 4: Add a DropDownList for the Categories (Click to view full-size image)

Next, from the DropDownList s smart tag, select the Choose Data Source option and create a new ObjectDataSource named CategoriesDataSource. Configure this ObjectDataSource to use the CategoriesBLL class s GetCategories() method (see Figure 5). Next, the DropDownList s Data Source Configuration Wizard prompts for the data fields to use for each ListItem s Text and Value properties. Have the DropDownList display the CategoryName data field and use the CategoryID as the value, as shown in Figure 6.

Create a New ObjectDataSource Named CategoriesDataSource

Figure 5: Create a New ObjectDataSource Named CategoriesDataSource (Click to view full-size image)

Configure the DropDownList s Display and Value Fields

Figure 6: Configure the DropDownList s Display and Value Fields (Click to view full-size image)

Repeat this series of steps to create a DropDownList for the suppliers. Set the ID for this DropDownList to Suppliers and name its ObjectDataSource SuppliersDataSource.

After adding the two DropDownLists, add a CheckBox for the discontinued state and a TextBox for the product s name. Set the ID s for the CheckBox and TextBox to Discontinued and ProductName, respectively. Add a RequiredFieldValidator to ensure that the user provides a value for the product s name.

Lastly, add the Update and Cancel buttons. Remember that for these two buttons it is imperative that their CommandName properties are set to Update and Cancel, respectively.

Feel free to lay out the editing interface however you like. I ve opted to use the same four-column <table> layout from the read-only interface, as the following declarative syntax and screen shot illustrates:

[!code-aspxMain]

   1:  <EditItemTemplate>
   2:      <h4>
   3:          <asp:Label ID="ProductNameLabel" runat="server"
   4:              Text='<%# Eval("ProductName") %>' />
   5:      </h4>
   6:      <table border="0">
   7:          <tr>
   8:              <td class="ProductPropertyLabel">Name:</td>
   9:              <td colspan="3" class="ProductPropertyValue">
  10:                  <asp:TextBox runat="server" ID="ProductName" Width="90%" />
  11:                  <asp:RequiredFieldValidator ID="RequiredFieldValidator1"
  12:                      ControlToValidate="ProductName"
  13:                      ErrorMessage="You must enter a name for the product."
  14:                      runat="server">*</asp:RequiredFieldValidator>
  15:              </td>
  16:          </tr>
  17:          <tr>
  18:              <td class="ProductPropertyLabel">Category:</td>
  19:              <td class="ProductPropertyValue">
  20:                  <asp:DropDownList ID="Categories" runat="server"
  21:                      DataSourceID="CategoriesDataSource"
  22:                      DataTextField="CategoryName" DataValueField="CategoryID" />
  23:              </td>
  24:              <td class="ProductPropertyLabel">Supplier:</td>
  25:              <td class="ProductPropertyValue">
  26:                  <asp:DropDownList ID="Suppliers"
  27:                      DataSourceID="SuppliersDataSource" DataTextField="CompanyName"
  28:                      DataValueField="SupplierID" runat="server" />
  29:              </td>
  30:          </tr>
  31:          <tr>
  32:              <td class="ProductPropertyLabel">Discontinued:</td>
  33:              <td class="ProductPropertyValue">
  34:                  <asp:CheckBox runat="server" id="Discontinued" />
  35:              </td>
  36:              <td class="ProductPropertyLabel">Price:</td>
  37:              <td class="ProductPropertyValue">
  38:                  <asp:Label ID="UnitPriceLabel" runat="server"
  39:                      Text='<%# Eval("UnitPrice", "{0:C}") %>' />
  40:              </td>
  41:          </tr>
  42:          <tr>
  43:              <td colspan="4">
  44:                  <asp:Button runat="Server" ID="UpdateButton" CommandName="Update"
  45:                      Text="Update" />
  46:                   
  47:                  <asp:Button runat="Server" ID="CancelButton" CommandName="Cancel"
  48:                      Text="Cancel" CausesValidation="False" />
  49:              </td>
  50:          </tr>
  51:      </table>
  52:      <br />
  53:      <asp:ObjectDataSource ID="CategoriesDataSource" runat="server"
  54:          OldValuesParameterFormatString="original_{0}" SelectMethod="GetCategories"
  55:          TypeName="CategoriesBLL">
  56:      </asp:ObjectDataSource>
  57:      <asp:ObjectDataSource ID="SuppliersDataSource" runat="server"
  58:          OldValuesParameterFormatString="original_{0}" SelectMethod="GetSuppliers"
  59:          TypeName="SuppliersBLL">
  60:      </asp:ObjectDataSource>
  61:  </EditItemTemplate>

The Editing Interface is Laid Out like the Read-Only Interface

Figure 7: The Editing Interface is Laid Out like the Read-Only Interface (Click to view full-size image)

Step 3: Creating the EditCommand and CancelCommand Event Handlers

Currently, there is no databinding syntax in the EditItemTemplate (except for the UnitPriceLabel, which was copied over verbatim from the ItemTemplate). We’ll add the databinding syntax momentarily, but first let s create the event handlers for the DataList s EditCommand and CancelCommand events. Recall that the responsibility of the EditCommand event handler is to render the editing interface for the DataList item whose Edit button was clicked, whereas the CancelCommand s job is to return the DataList to its pre-editing state.

Create these two event handlers and have them use the following code:

[!code-vbMain]

   1:  Protected Sub Products_EditCommand(source As Object, e As DataListCommandEventArgs) _
   2:      Handles Products.EditCommand
   3:      ' Set the DataList's EditItemIndex property to the
   4:      ' index of the DataListItem that was clicked
   5:      Products.EditItemIndex = e.Item.ItemIndex
   6:      ' Rebind the data to the DataList
   7:      Products.DataBind()
   8:  End Sub
   9:  Protected Sub Products_CancelCommand(source As Object, e As DataListCommandEventArgs) _
  10:      Handles Products.CancelCommand
  11:      ' Set the DataList's EditItemIndex property to -1
  12:      Products.EditItemIndex = -1
  13:      ' Rebind the data to the DataList
  14:      Products.DataBind()
  15:  End Sub

With these two event handlers in place, clicking the Edit button displays the editing interface and clicking the Cancel button returns the edited item to its read-only mode. Figure 8 shows the DataList after the Edit button has been clicked for Chef Anton s Gumbo Mix. Since we ve yet to add any databinding syntax to the editing interface, the ProductName TextBox is blank, the Discontinued CheckBox unchecked, and the first items selected from the Categories and Suppliers DropDownLists.

Clicking the Edit Button Displays the Editing Interface

Figure 8: Clicking the Edit Button Displays the Editing Interface (Click to view full-size image)

Step 4: Adding the DataBinding Syntax to the Editing Interface

To have the editing interface display the current product s values, we need to use databinding syntax to assign the data field values to the appropriate Web control values. The databinding syntax can be applied through the Designer by going to the Edit Templates screen and selecting the Edit DataBindings link from the Web controls smart tags. Alternatively, the databinding syntax can be added directly to the declarative markup.

Assign the ProductName data field value to the ProductName TextBox s Text property, the CategoryID and SupplierID data field values to the Categories and Suppliers DropDownLists SelectedValue properties, and the Discontinued data field value to the Discontinued CheckBox s Checked property. After making these changes, either through the Designer or directly through the declarative markup, revisit the page through a browser and click the Edit button for Chef Anton s Gumbo Mix. As Figure 9 shows, the databinding syntax has added the current values into the TextBox, DropDownLists, and CheckBox.

Clicking the Edit Button Displays the Editing Interface

Figure 9: Clicking the Edit Button Displays the Editing Interface (Click to view full-size image)

Step 5: Saving the User s Changes in the UpdateCommand Event Handler

When the user edits a product and clicks the Update button, a postback occurs and the DataList s UpdateCommand event fires. In the event handler, we need to read the values from the Web controls in the EditItemTemplate and interface with the BLL to update the product in the database. As we ve seen in previous tutorials, the ProductID of the updated product is accessible through the DataKeys collection. The user-entered fields are accessed by programmatically referencing the Web controls using FindControl("controlID"), as the following code shows:

[!code-vbMain]

   1:  Protected Sub Products_UpdateCommand(source As Object, e As DataListCommandEventArgs) _
   2:      Handles Products.UpdateCommand
   3:      If Not Page.IsValid Then
   4:          Exit Sub
   5:      End If
   6:      ' Read in the ProductID from the DataKeys collection
   7:      Dim productID As Integer = Convert.ToInt32(Products.DataKeys(e.Item.ItemIndex))
   8:      ' Read in the product name and price values
   9:      Dim productName As TextBox = CType(e.Item.FindControl("ProductName"), TextBox)
  10:      Dim categories As DropDownList=CType(e.Item.FindControl("Categories"), DropDownList)
  11:      Dim suppliers As DropDownList = CType(e.Item.FindControl("Suppliers"), DropDownList)
  12:      Dim discontinued As CheckBox = CType(e.Item.FindControl("Discontinued"), CheckBox)
  13:      Dim productNameValue As String = Nothing
  14:      If productName.Text.Trim().Length > 0 Then
  15:          productNameValue = productName.Text.Trim()
  16:      End If
  17:      Dim categoryIDValue As Integer = Convert.ToInt32(categories.SelectedValue)
  18:      Dim supplierIDValue As Integer = Convert.ToInt32(suppliers.SelectedValue)
  19:      Dim discontinuedValue As Boolean = discontinued.Checked
  20:      ' Call the ProductsBLL's UpdateProduct method...
  21:      Dim productsAPI As New ProductsBLL()
  22:      productsAPI.UpdateProduct(productNameValue, categoryIDValue, supplierIDValue, _
  23:          discontinuedValue, productID)
  24:      ' Revert the DataList back to its pre-editing state
  25:      Products.EditItemIndex = -1
  26:      Products.DataBind()
  27:  End Sub

The code starts out by consulting the Page.IsValid property to ensure that all the validation controls on the page are valid. If Page.IsValid is True, the edited product s ProductID value is read from the DataKeys collection and the data entry Web controls in the EditItemTemplate are programmatically referenced. Next, the values from these Web controls are read into variables that are then passed into the appropriate UpdateProduct overload. After updating the data, the DataList is returned to its pre-editing state.

[!NOTE] I ve omitted the exception handling logic added in the Handling BLL- and DAL-Level Exceptions tutorial in order to keep the code and this example focused. As an exercise, add this functionality after completing this tutorial.

Step 6: Handling NULL CategoryID and SupplierID Values

The Northwind database allows for NULL values for the Products table s CategoryID and SupplierID columns. However, our editing interface doesn t currently accommodate NULL values. If we attempt to edit a product that has a NULL value for either its CategoryID or SupplierID columns, we’ll get an ArgumentOutOfRangeException with an error message similar to: ‘Categories’ has a SelectedValue which is invalid because it does not exist in the list of items. Also, there s currently no way to change a product s category or supplier value from a non-NULL value to a NULL one.

To support NULL values for the category and supplier DropDownLists, we need to add an additional ListItem. I ve chosen to use (None) as the Text value for this ListItem, but you can change it to something else (such as an empty string) if you d like. Finally, remember to set the DropDownLists AppendDataBoundItems to True; if you forget to do so, the categories and suppliers bound to the DropDownList will overwrite the statically-added ListItem.

After making these changes, the DropDownLists markup in the DataList s EditItemTemplate should look similar to the following:

[!code-aspxMain]

   1:  <asp:DropDownList ID="Categories" DataSourceID="CategoriesDataSource"
   2:      DataTextField="CategoryName" DataValueField="CategoryID"  runat="server"
   3:      SelectedValue='<%# Eval("CategoryID") %>' AppendDataBoundItems="True">
   4:      <asp:ListItem Value=" Selected="True">(None)</asp:ListItem>
   5:  </asp:DropDownList>
   6:  ...
   7:  <asp:DropDownList ID="Suppliers" DataSourceID="SuppliersDataSource"
   8:      DataTextField="CompanyName" DataValueField="SupplierID" runat="server"
   9:      SelectedValue='<%# Eval("SupplierID") %>' AppendDataBoundItems="True">
  10:      <asp:ListItem Value=" Selected="True">(None)</asp:ListItem>
  11:  </asp:DropDownList>

[!NOTE] Static ListItem s can be added to a DropDownList through the Designer or directly through the declarative syntax. When adding a DropDownList item to represent a database NULL value, be sure to add the ListItem through the declarative syntax. If you use the ListItem Collection Editor in the Designer, the generated declarative syntax will omit the Value setting altogether when assigned a blank string, creating declarative markup like: <asp:ListItem>(None)</asp:ListItem>. While this may look harmless, the missing Value causes the DropDownList to use the Text property value in its place. That means that if this NULL ListItem is selected, the value (None) will be attempted to be assigned to the product data field (CategoryID or SupplierID, in this tutorial), which will result in an exception. By explicitly setting Value="", a NULL value will be assigned to the product data field when the NULL ListItem is selected.

Take a moment to view our progress through a browser. When editing a product, note that the Categories and Suppliers DropDownLists both have a (None) option at the start of the DropDownList.

The Categories and Suppliers DropDownLists include a (None) Option

Figure 10: The Categories and Suppliers DropDownLists include a (None) Option (Click to view full-size image)

To save the (None) option as a database NULL value, we need to return to the UpdateCommand event handler. Change the categoryIDValue and supplierIDValue variables to be nullable integers and assign them a value other than Nothing only if the DropDownList s SelectedValue is not an empty string:

[!code-vbMain]

   1:  Dim categoryIDValue As Nullable(Of Integer) = Nothing
   2:  If Not String.IsNullOrEmpty(categories.SelectedValue) Then
   3:      categoryIDValue = Convert.ToInt32(categories.SelectedValue)
   4:  End If
   5:  Dim supplierIDValue As Nullable(Of Integer) = Nothing
   6:  If Not String.IsNullOrEmpty(suppliers.SelectedValue) Then
   7:      supplierIDValue = Convert.ToInt32(suppliers.SelectedValue)
   8:  End If

With this change, a value of Nothing will be passed into the UpdateProduct BLL method if the user selected the (None) option from either of the drop-down lists, which corresponds to a NULL database value.

Summary

In this tutorial we saw how to create a more complex DataList editing interface that included three different input Web controls a TextBox, two DropDownLists, and a CheckBox along with validation controls. When building the editing interface, the steps are the same regardless of the Web controls being used: start by adding the Web controls to the DataList s EditItemTemplate; use databinding syntax to assign the corresponding data field values with the appropriate Web control properties; and, in the UpdateCommand event handler, programmatically access the Web controls and their appropriate properties, passing their values into the BLL.

When creating an editing interface, whether it s composed of just TextBoxes or a collection of different Web controls, be sure to correctly handle database NULL values. When accounting for NULL s, it is imperative that you not only correctly display an existing NULL value in the editing interface, but also that you offer a means for marking a value as NULL. For DropDownLists in DataLists, that typically means adding a static ListItem whose Value property is explicitly set to an empty string (Value=""), and adding a bit of code to the UpdateCommand event handler to determine whether or not the NULL``ListItem was selected.

Happy Programming!

About the Author

Scott Mitchell, author of seven ASP/ASP.NET books and founder of 4GuysFromRolla.com, has been working with Microsoft Web technologies since 1998. Scott works as an independent consultant, trainer, and writer. His latest book is Sams Teach Yourself ASP.NET 2.0 in 24 Hours. He can be reached at mitchell@4GuysFromRolla.com. or via his blog, which can be found at http://ScottOnWriting.NET.

Special Thanks To

This tutorial series was reviewed by many helpful reviewers. Lead reviewers for this tutorial were Dennis Patterson, David Suru, and Randy Schmidt. Interested in reviewing my upcoming MSDN articles? If so, drop me a line at mitchell@4GuysFromRolla.com.

Previous



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-forms/overview/data-access/editing-and-deleting-data-through-the-datalist/customizing-the-datalist-s-editing-interface-vb.htm
< THANKS ME>