ASP. NET Composite Control triggers data binding events

Source: Internet
Author: User

Generate a Data Binding ASP. NET Composite Control

Most complex server controls are bound to data or templated) and are composed of various seed controls. These controls retain a list of rows or cells that normally constitute a table. After sending the list back, it is saved in the view State and generated from the bound data or rebuilt from the view State. This control also saves the number of its constituent items in the view State, so that the table structure can be correctly rebuilt when other controls on the page cause a return. The DataGrid control is used as an example.

A DataGrid consists of one row. Each row represents a record bound to the data source. Each grid row is represented by a class derived from TableRow by a DataGridRow object. When a grid row is created and added to the final grid table, events such as ItemCreated and ItemDataBound are triggered to the page. When you create a DataGrid through data binding, the number of rows is determined by the number of bound items and page size. What if a page with a DataGrid is sent back?

In this case, if the response is caused by the DataGrid itself, for example, the user clicks to sort or label the page), the new page will be displayed through data binding again. This is obvious, because the DataGrid needs to refresh the data for display. For homepage sending back, the situation is different, because another control on the page, such as a button, is clicked ). In this case, the DataGrid is not bound to the data and must be rebuilt from the view State. If the view status is disabled, the display grid can only be displayed through data binding .)

The data source is not saved in the view State. As a composite control, the DataGrid contains child controls. Each child control saves its own state to the view State and restores it from the view State. The DataGrid only needs to track the number of times it must be repeated before all rows and controls are restored from the view State. This number is the same as the number of bound items displayed, and must be stored as part of the control status to the view status. In ASP. NET 1.x, you must learn and implement this mode on your own. In ASP. NET 2.0, You can derive your composite control from the CompositeDataBoundControl class.

Let's try to use a grid-like control that displays extensible data bound to a news title line. In this process, we will use the Headline control discussed previously.

 
 
  1. public class HeadlineListEx :CompositeDataBoundControl  
  2. {  
  3.   :  
  4. }  

The HeadlineListEx control contains an Items set property that collects all bound data Items. This set is a public set and can be filled in programmatically when running with most list controls. The support for typical data binding is achieved through a pair of attribute DataTextField and DataTitleField. These two attributes indicate fields in the data source that will be used to fill the news title and text. The Items set is saved to the view State.

To convert the HeadlineListEx control to a real ASP. NET Composite Control, you must first derive it from CompositeDataBoundControl and then replace CreateChildControls. Interestingly, you will notice that CreateChildControls is an overload method.

 
 
  1. override int CreateChildControls()  
  2. override int CreateChildControls(IEnumerable data, bool dataBinding)  

The first overload method replaces the method defined in the Control class. The second overload method is an abstract method that must be replaced by each composite control. In fact, the development of composite controls is simplified to two main tasks:

Replace CreateChildControls.

Implement the Rows set attribute to track all components of the control.

The Rows attribute is different from the Items attribute because it is not stored in the view State and has the same lifetime as the request, and references the help program object instead of Binding data Items.

 
 
  1. public virtual HeadlineRowCollection Rows  
  2. {  
  3. get 
  4.     {  
  5. if (_rows == null)  
  6. _rows = new HeadlineRowCollection();  
  7. return _rows;  
  8.      }  
  9. }  

The Rows set is filled when the control is generated. Let's take a look at the CreateChildControls replacement method. This method uses two parameters: the binding item and a Boolean tag. The Boolean tag indicates whether the control is created by data binding or by view status. Note that the programmer comments in the example program file are in English. In this document, they are translated into Chinese for reference .)

 
 
  1. Override IntCreateChildControls (IEnumerable dataSource,BoolDataBinding)
  2. {
  3. If(DataBinding)
  4. {
  5. StringTextField = DataTextField;
  6. StringTitleField = DataTitleField;
  7. If(DataSource! =Null)
  8. {
  9. Foreach(ObjectOInDataSource)
  10. {
  11. HeadlineItem elem =NewHeadlineItem ();
  12. Elem. Text = DataBinder. GetPropertyValue (o, textField,Null);
  13. Elem. Title = DataBinder. GetPropertyValue (o, titleField,Null);
  14. Items. Add (elem );
  15. }
  16. }
  17. }
  18.  
  19. // Start generating the control hierarchy 
  20. Table t =NewTable ();
  21. Controls. Add (t );
  22. Rows. Clear ();
  23. IntItemCount = 0;
  24.  
  25. Foreach(HeadlineItem itemInItems)
  26. {
  27. HeadlineRowType type = HeadlineRowType. Simple;
  28. HeadlineRow row = CreateHeadlineRow (t, type,
  29. Item, itemCount, dataBinding );
  30. _ Rows. Add (row );
  31. ItemCount ++;
  32. }
  33.  
  34. ReturnItemCount;
  35. }
  36.  

When binding data, you must first fill in the Items set. Traverse the bound set, extract data, and then fill in the new instance of the HeadlineItem class. Next, traverse the Items set. This set may contain additional Items that are added programmatically.

 
 
  1. HeadlineRow CreateHeadlineRow (Table t, HeadlineRowType rowType,
  2. HeadlineItem dataItem,IntIndex,BoolDataBinding)
  3. {
  4. // Create a new row for the most external table 
  5. HeadlineRow row =NewHeadlineRow (rowType );
  6.  
  7. // Create a cell for the Child Control 
  8. TableCell cell =NewTableCell ();
  9. Row. Cells. Add (cell );
  10. Headline item =NewHeadline ();
  11. Cell. Controls. Add (item );
  12.  
  13. // The HeadlineRowCreated event is triggered. 
  14.  
  15. // Add this row to the created HTML table 
  16. T. Rows. Add (row );
  17.  
  18. // Bind the processing data object 
  19. If(DataBinding)
  20. {
  21. Row. DataItem = dataItem;
  22. Headline ctl = (Headline) cell. Controls [0];
  23. Ctl. Text = dataItem. Text;
  24. Ctl. Title = dataItem. Title;
  25. // The HeadlineRowDataBound event is triggered. 
  26. }
  27. ReturnRow;
  28. }
  29.  

The CreateHeadlineRow method creates and returns an instance of the HeadlineRow class derived from TableRow. In this case, the row contains a cell filled with the Headline control. In other cases, you can change this part of code to add multiple cells as needed and fill the content accordingly.

It is important to divide the tasks to be completed into two different steps: Creation and data binding. First, create a row layout, raise the row creation event if any), and add it to the parent table. Next, if you want to bind the control to data, set the attributes of the Child control that is sensitive to data binding. After the operation is completed, a row data binding event is triggered if any ).

Note that this mode accurately describes the internal architecture of ASP. NET composite controls.

You can use the following code to raise an event.

 
 
  1. HeadlineRowEventArgs e = new HeadlineRowEventArgs();  
  2. e.DataItem = dataItem;  
  3. e.RowIndex = index;  
  4. e.RowType = rowType;  
  5. e.Item = row;  
  6. OnHeadlineRowDataBound(e);  

Note that the DataItem attribute is set only when a data binding event is triggered. The event data structure is set as follows. If you think it is necessary, do your best to change it.

 
 
  1. public class HeadlineRowEventArgs :EventArgs  
  2. {  
  3. public HeadlineItem DataItem;  
  4. public HeadlineRowType RowType;  
  5. public int RowIndex;  
  6. public HeadlineRow Item;  
  7. }  

To actually trigger an event, we usually use a protected method as defined below.

 
 
  1. protected virtual void OnHeadlineRowDataBound(HeadlineRowEventArgs e)  
  2. {  
  3. if (HeadlineRowDataBound != null)  
  4. HeadlineRowDataBound(this, e);  
  5. }  

To declare this event, you can use the new general event handler delegate in ASP. NET 2.0.

 
 
  1. public event EventHandler< HeadlineRowEventArgs> HeadlineRowDataBound;  

On the example Page, everything is executed as usual. You can define the handler on the control tag and write a method to the code file. Example.

 
 
  1. < cc1:HeadlineListEx runat="server" ID="HeadlineListEx1"   
  2. DataTextField="notes" DataTitleField="lastname"   
  3. DataSourceID="MySource" OnHeadlineRowDataBound="HeadlineRowCreated" /> 

The code of the HeadlineRowCreated event handler is as follows.

 
 
  1. protected void HeadlineRowCreated(object sender, HeadlineRowEventArgs e)  
  2. {  
  3. if (e.DataItem.Title.Contains("Doe"))  
  4. e.Item.BackColor = Color.Red;  
  5. }  
  6.   

 

Figure 7: Running HeadlineListEx Control

By mounting a Data Binding event, all items containing Doe are displayed in a red background.

  1. ASP. NET composite controls and CompositeControl
  2. Rendering Engine of ASP. NET composite controls
  3. Overview of ASP. NET composite controls
  4. Analysis on Composite Control Event Processing Based on ASP. NET control development
  5. Analysis of compound controls based on ASP. NET control development

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.