Operating data 45 in asp.net 2.0: custom button_ self-study process in DataList and repeater

Source: Internet
Author: User
Tags bind eval

Introduction

In the previous 7 chapters on DataList and Repeater, we created examples of read-only and editable deletes. In order for DataList to have Edit and delete functions, we have added some button in the ItemTemplate, when clicked, causes postback, and fires the related event according to the button's CommandName property. For example, adding a button commandname to "Edit" fires the EditCommand event when postback, and fires DeleteCommand if CommandName is "Delete".

In addition to editing and deleting button,datalist and repeater, you can also include some Button,linkbutton and ImageButton that implement custom server-side logic when clicked. In this chapter we will create an interface that lists categories in repeater. Each category contains a button that lists the related product when clicked. See Figure 1.


Figure 1: Point "show Products" Display directory all product

Step One: Add a tutorial page

First add the pages that this chapter requires. Add a folder named Custombuttonsdatalistrepeater. Then add the following two pages and remember to include the Site.master master page.

Default.aspx
Custombuttons.aspx


Figure 2: Add page

As with other folders, the Default.aspx page in the Custombuttonsdatalistrepeater folder lists the tutorials in this section. Add the Sectionleveltutoriallisting.ascx user control as before.


Figure 3: Adding the Sectionleveltutoriallisting.ascx user Control

Finally, add the information for these pages in the Web.sitemap. See the following tag:

<sitemapnode
 url= "~/custombuttonsdatalistrepeater/default.aspx"
 title= "adding Custom Buttons to the" DataList and Repeater "
 description=" Samples of DataList and Repeater Reports that Include
     Buttons for performing S Erver-side Actions ">
 <sitemapnode
  url=" ~/custombuttonsdatalistrepeater/custombuttons.aspx "
  title= "Using Custom Buttons in the DataList and Repeater's Templates"
  description= "examines how to add Custom Buttons, LinkButtons,
      or imagebuttons within templates. "/>
</siteMapNode>

Browse the page when you are finished. See Figure 4.


Figure 4: The site map now contains the pages of this chapter

Step Two: Add categories list

We need to add a list of all the categories, each category has a "show products" LinkButton repeater. All category-related products will be displayed when LinkButton. We first create a repeater that lists all the categories. Open the Custombuttons.aspx page, drag a repeater in, and set the ID to categories. Then create a ObjectDataSource named Categoriesdatasource from the smart tag and configure it with the GetCategories () method of the Categoriesbll class.


Figure 5: Configuring ObjectDataSource

Visual Studio creates a default ItemTemplate for DataList based on the data source, and repeater templates need to be manually defined. And repeater's Templates need to be created and modified directly by declaring code (i.e. there is no "Edit Templates" option on the smart tag)

Point to the bottom left corner of the source view, add a

<asp:repeater id= "Categories" datasourceid= "Categoriesdatasource"
 runat= "Server" >
 <itemtemplate >
   
 

Figure 6 is how you view the page. Each category name and description are listed. When the "Show products" button causes postback, it does not perform any functions.


Figure 6: Each Category ' name and Description are listed together with the show products LinkButton

Step three: Execute the server-side code when the "Show products" LinkButton.

At any time, when the button, LinkButton, and ImageButton in the template of DataList or Repeater is clicked, a postback is generated, And to excite DataList or repeater ItemCommand events. In addition to ItemCommand, if one of the button's CommandName is set to ("Delete", "Edit", "Cancel", "Update", "select"), DataList fires another event. But the ItemCommand will inspire.

When the button in the DataList or Repeater template is clicked, usually we need to get which button is clicked (a control may have multiple button, such as Edit and delete), You may also need some additional information, such as the primary key of the item that the button is clicked on. Button, LinkButton, ImageButton provides two properties, and their values can be passed to ItemCommand event handler:

commandname– a string representing the identity of each button in the template.
commandargument– is often used to hold values, such as primary keys.

In this example, the LinkButton CommandName is set to "Showproducts" and the primary key –categoryid– of the current record is bound to commandargument through the binding syntax (categoryargument= ' <%# Eval (' CategoryID ')%> '). Once this is done, the LinkButton declaration syntax should look similar to the following:

<asp:linkbutton runat= "Server" Commandname= "showproducts"
 commandargument= ' <%# Eval ("CategoryID")%> ' Id= "Showproducts" > Show
 products</asp:linkbutton>

When the button is clicked, it generates postback and fires the ItemCommand event of the DataList or repeater. The CommandName and CommandArgument values of the button were passed to event handler.

Create an event handler for the ItemCommand event, noting the second argument of event handler (name E). The type of this parameter is RepeaterCommandEventArgs, which has the following 4 properties:

commandargument– the value of the CommandArgument property of the button ' that was clicked
Value of the CommandName property of Commandname–button '
commandsource– is referenced by the dot button
The item– contains a reference to the RepeaterItem of the point button; Each record bound to repeater is indicated as a RepeaterItem

Due to the selection of the category CategoryID passed through the CommandArgument, we can obtain the related products in ItemCommand event handler. These products are bound to a bulletedlist in the ItemTemplate (which we have already added). The rest is to add bulletedlist, reference it in ItemCommand event handler, and then bind the selected category products to BulletedList, which we will do in step fourth.

  Note: DataList's ItemCommand event handler passed in a DataListCommandEventArgs-type object that provides the same 4 attributes as the RepeaterCommandEventArgs.

Fourth step: Show selected products of category

Show products in ItemTemplate can use a lot of controls, we can add a nested repeater,datalist,dropdownlist,gridview and so on. Here we use the BulletedList. Return to the Custombuttons.aspx page declaration code and add a bulletedlist after the show products LinkButton. Set the ID to productsincategory. BulletedList displays the values of the fields that are specified by the DataTextField property. Because the product information is bound to this property, we set the DataTextField to ProductName.

<asp:bulletedlist id= "Productsincategory" datatextfield= "ProductName" runat=
 "Server" ></asp: Bulletedlist>

In ItemCommand event handler through E. Item.findcontrol ("productsincategory") references this control and binds to the products.

protected void Categories_itemcommand (object source, RepeaterCommandEventArgs e)
{
 if (E.commandname = = " Showproducts ")
 {
  //determine the CategoryID
  int categoryid = Convert.ToInt32 (e.commandargument);
  Get the associated products from the PROUDCTSBLL and bind
  //them to the BulletedList
  BulletedList products =
    (BulletedList) E.item.findcontrol ("Productsincategory");
  PRODUCTSBLL Productsapi = new Productsbll ();
  Products. DataSource =
   Productsapi.getproductsbycategoryid (CategoryID);
  Products. DataBind ());
 }

Before you perform any action in the ItemCommand event handler, you need to check the incoming CommandName first. Because the ItemCommand event handler executes when any button is clicked, if there is more than one button in template, the CommandName value is required to identify what action needs to be taken. Since we have only one button here, it's pointless to check commandname here, but it's a good habit. Then, the selected category CategoryID is obtained by CommandArgument. It then references the BulletedList in template and binds the results of the Getproductsbycategoryid (CategoryID) method of the Productsbll class.

In the tutorial on using the button in the previous DataList, such as editing and deleting the data in DataList, we get the primary key for the given item through the DataKeys collection. This method works well in DataList, but Repeater has no datakeys attributes. So we need a different way to provide the value of the primary key, such as through the button's commandargument, or using a hidden label in template, and then through E. Item.findcontrol ("Labelid") reads its value in ItemCommand event handler.

After completing the ItemCommand event handler, browse to the page. See Figure 7. Point "show products" link will cause postback, and display related products. Also, note that the previous product information is retained when you point to other "show products" links.

  Note: If you need to modify the behavior of this report, such as listing only one category products at a time, simply set the BulletedList EnableViewState property to False.


Figure 7: Display the selected products with category associated with BulletedList.

Summarize

DataList and repeater can include many buttons, linkbuttons, and imagebuttons in the templates. These button points can cause postback and fire the ItemCommand event. For ItemCommand event. Create an event handler can associate the server-side code with the click button. In this event handler first check the value of the incoming CommandName to determine which button was clicked. Additional information can be provided through the CommandArgument property.

I wish you a happy programming!

Introduction of the author

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.

Related Article

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.