Manipulating data in ASP.net 2.0 40: Customizing DataList Editing Interface _ self-study process

Source: Internet
Author: User

Introduction

The DataList editing interface is defined by the markup language and Web controls in EditItemTemplate. In the example of the DataList editing function so far, the editing interface contains only the TextBox. In the previous chapter, we added validation controls to increase the user experience and increase usability.

EditItemTemplate can contain many controls other than the textbox, such as DropDownList, RadioButtonList, Calendar, and so on. As with the textbox, when you use these controls to customize the editing interface, the steps are as follows:

Add controls for EditItemTemplate.
Use the binding syntax to assign related field values to the properties of the control.
In UpdateCommand event processing, you programmatically access the value of a Web control and pass it to the associated BLL method.

In this chapter we will create a richer editing interface for DataList, which will contain DropDownList and checkbox. We will create a DataList that lists the product information, and the user can update its name,supplier,category and discontinued status. See Figure 1.


Figure 1: The editing interface contains a textbox, two dropdownlists, and a checkbox

First step: Display product information

We need to create a read-only interface before creating the DataList editor. First open the Customizedui.aspx page under the Editdeletedatalist folder, drag a DataList in, and set the ID to products. Through the smart tag of DataList, create a ObjectDataSource named Productsdatasource, configure it with the GetProducts method of the Productsbll class. As in the previous chapter, we will update the product information directly through BLL. Select None in the Update,insert,delete tab.


Figure 2: Select (None) in the Drop-down list of the update, INSERT, DELETE tab

When you finish configuring ObjectDataSource, Visual Studio automatically creates a default ItemTemplate that lists the values for each field. Use product name with

<ItemTemplate>  

The markup language above uses


Figure 3: Displaying product information

Step Two: Add Web controls for the edit interface

First, add the required Web controls to the EditItemTemplate. We need to use a DropDownList to represent the category, a DropDownList to represent supplier, and a checkbox to represent the discontinued state. Because the price is not edited in this example, it is still represented by a label.

Click "Edit Templates" on DataList's Smart tab and select EditItemTemplate to add a EditItemTemplate with ID categories.


Figure 4: Adding a DropDownList for categories

Then select "Choose Data Source" from DropDownList's smart tag and create a ObjectDataSource named Categoriesdatasource. It is prepared using the GetCategories () method of the Categoriesbll class (see Figure 5). The Data Source Configuration Wizard requires the field to be selected for ListItem text and value. Let DropDownList display Categoryname,categoryid as value, see Figure 6.


Figure 5: Creating ObjectDataSource


Figure 6: Configuring the Display field and Value field for DropDownList

Repeat the steps above to create a DropDownList with ID suppliers and a ObjectDataSource named Suppliersdatasource for suppliers.

Then add a checkbox for discontinued state and a textbox for name. Set their IDs to discontinued and ProductName respectively. Add a RequiredFieldValidator to product name to ensure that the user must provide this value.

Finally, add the update and Cancel button. Remember that the CommandName properties of these two button must be set to "Update" and "Cancel" respectively. You can display the editing interface in the way you like. I choose to use the same interface as the read-only interface to display, see the following declaration code and screenshots.

<EditItemTemplate> 

protected void Products_editcommand (object source, DataListCommandEventArgs e)
{
 //Set the DataList ' s EditItemIndex property and rebind the data
 products.edititemindex = E.item.itemindex;
 Products.databind ();
}
protected void Products_cancelcommand (object source, DataListCommandEventArgs e)
{
 //return to DataList to its pre-editing State
 Products.edititemindex =-1;
 Products.databind ();
}

When this is done, clicking on the Edit button will enter the editing screen, and clicking the Cancel button returns read-only mode. See Figure 8. Since no binding syntax has been added for the editing interface, the textbox is blank and the CheckBox is not selected, and the first item in the two DropDownList is selected.


Figure 8: Click Edit button to display the editing interface

Step Fourth: Add binding syntax for the edit interface

In order for the editing interface to display the current product value, we need to assign the value of the field to the Web control using the binding syntax. The binding syntax can be implemented by selecting the "Edit databindings" of a Web control's smart tag or by adding a declaration syntax directly.

Assign the value of the ProductName field to the Text property of the ProductName textbox, CategoryID and SupplierID fields to categories and suppliers The SelectedValue property of the DropDownList, discontinued field assigned to the checked property of the Discontinued checkbox. When you are done, browse the page and click the Edit button. See Figure 9.


Figure 9: Click Edit Button to display the editing interface

Fifth step: Save user's changes in UpdateCommand Event handler

When the user edits the product and then points to the Update button, the UpdateCommand event is postback and fired. In event handling, we need to read the value of the Web control from the EditItemTemplate, interact with BLL, and then update the product in the database. As we saw in the previous chapter, the ProductID of the updated product can be obtained by the DataKeys collection. The value entered by the user can be obtained programmatically by FindControl ("ControlID"), as shown in the following code:

protected void Products_updatecommand (object source, DataListCommandEventArgs e) {//Make sure the page is valid ... if (!
 Page.IsValid) return; Read in the ProductID from the DataKeys collection int ProductID = Convert.ToInt32 (Products.datakeys[e.item.itemindex)
 );
 Read in the product name and price values TextBox productName = (TextBox) e.item.findcontrol ("ProductName");
 DropDownList categories = (DropDownList) e.item.findcontrol ("categories");
 DropDownList suppliers = (DropDownList) e.item.findcontrol ("Suppliers");
 CheckBox discontinued = (checkbox) E.item.findcontrol ("discontinued");
 string productnamevalue = null; if (ProductName.Text.Trim ().
 Length > 0) productnamevalue = ProductName.Text.Trim (); int categoryidvalue = Convert.ToInt32 (categories.
 SelectedValue); int supplieridvalue = Convert.ToInt32 (suppliers.
 SelectedValue); BOOL Discontinuedvalue = discontinued.
 Checked;
 Call the Productsbll ' s updateproduct ... PRODUCTSBLL Productsapi = new PRODUCTSBLL ();
 Productsapi.updateproduct (Productnamevalue, Categoryidvalue, Supplieridvalue, Discontinuedvalue, ProductID);
 Revert the pre-editing state products.edititemindex =-1;
Products.databind ();
 }

The code first checks the Page.IsValid property to ensure that all validation controls return legitimate values. If Page.IsValid is true, the value of the ProductID of the edited product is read from the DataKeys collection, and the Web control in EditItemTemplate is referenced. The values of these controls are then read into the variable and passed to the UpdateProduct method. When the update is complete, DataList returns to the state before the edit.

Note: I omitted a chapter exception handling to make the code in this chapter look more purposeful. You can add your own exception handling function as an exercise after completing this chapter.

Step Sixth: Handle empty CategoryID and SupplierID values

The Northwind database allows the CategoryID and SupplierID columns in the Products table to be empty. However, our editing interface has not yet provided an optional null value. If we try to edit a product that is either CategoryID or SupplierID, a ArgumentOutOfRangeException exception will be generated. At present, we do not have a method to convert the value of product category or supplier from one non-null value to a null value.

To add a null value to the dropdownlists, we need to add a listitem. I display the text in ListItem as "(None)" And you can assign it to any value you want (such as an empty string). Finally, remember to set the Dropdownlists AppendDataBoundItems to True. If you do not, the categories and suppliers that are bound to DropDownList will be overwritten by the added ListItem. Once this is done, the Dropdownlists markup language should look similar to the following:

 <asp:dropdownlist id= "Categories" datasourceid= "Categoriesdatasource" Datatextfield= "CategoryName" datavaluefield= "CategoryID" runat= "Server" selectedvalue= ' <%# ' Eval ("CategoryID")% > ' appenddatabounditems= true ' > <asp:listitem value= ' selected= ' true ' > (None) </asp:ListItem> </ Asp:dropdownlist> ... <asp:dropdownlist id= "Suppliers datasourceid=" Suppliersdatasource "DataTextField=" CompanyName "datavaluefield=" SupplierID "runat=" Server "selectedvalue=" <%# Eval ("SupplierID")%> ' Appenddatabounditems= "true" > <asp:listitem value= "selected=" true "> (None) </asp:ListItem> </asp:d Ropdownlist> 

  Note: Adding ListItems for DropDownList can be done through the designer or declarative syntax. When you add an item that represents a null value for a database, make sure it is done by declaring the syntax. If you use the designer's ListItem collection Editor, when you assign an empty string, the resulting declaration syntax ignores the setting of value, resulting in statements like <asp:ListItem> (None) </asp:ListItem>. This does not seem to matter, but the lack of value allows DropDownList to use the value of the text attribute as value. This means that when a null ListItem is selected, "(None)" is assigned to the product's CategoryID or SupplierID field, which causes an exception. The value is explicitly set to "", and a null value is assigned to the product's CategoryID or SupplierID field when the null ListItem is selected. Now browse the page. When editing product, note that the categories and suppliers dropdownlists contain a "(None)" option at the beginning.


Figure 10:categories and Suppliers dropdownlists contains "(None)"

In order to save "(None)" as a database null value, we need to go back to UpdateCommand event handling. Sets the Categoryidvalue and supplieridvalue variables to nullable integers and assigns values to DropDownList SelectedValue values that are not empty strings.

Int? Categoryidvalue = null;
if (!string. IsNullOrEmpty (categories. SelectedValue))
 Categoryidvalue = Convert.ToInt32 (categories. SelectedValue);
Int? Supplieridvalue = null;
if (!string. IsNullOrEmpty (suppliers. SelectedValue))
 Supplieridvalue = Convert.ToInt32 (suppliers. SelectedValue);

When this is done, if the user selects "(None)" in DropDownList, a null value is passed to the UpdateProduct BLL method, which is equivalent to the null value of the database.

Summarize

In this chapter we learned how to create a more complex editing interface for DataList, which contains three different Web controls-a textbox, two dropdownlists, and a checkbox-and contains validation controls. When you create an editing interface, the steps are the same regardless of which control is used: First, add the controls to the EditItemTemplate, assign the field values to the properties of the corresponding Web control through the binding syntax, and programmatically access the Web controls and their properties in UpdateCommand event processing. and pass the value to BLL.

When creating an editing interface, whether it consists of only a TextBox or a different Web control, make sure that the database null value is handled correctly. When handling null, you need not only to display the existing null values correctly in the editing interface, but also to provide a way to enter null values. For dropdownlists in datalists, this usually means adding a Value property that is explicitly set to an empty string (value= "") ListItem, and then determining NULL in UpdateCommand event handling Whether the ListItem is selected.

I wish you a happy programming!

Author Introduction

Scott Mitchell, author of this series of tutorials, has six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. You can click to see all Tutorials "[translation]scott Mitchell asp.net 2.0 data tutorial," I hope to learn asp.net help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.