DataGrid, datalist, Repeater

Source: Internet
Author: User

This is what I found online.
Itemdatabound, itemcreated
The first thing we should talk about is the time when these two events occurred.
Itemdatabound: If you execute the databind method, this event will be immediately triggered.
Itemcreated, if the page is accessed for the first time (page. ispostback = false). When databind is executed for the first time, the itemcreated event is first triggered. That is to say, after databind is executed, itemcreated is used to create header rows first, then, itemdatabound is used to bind the header row, itemcreated is used to create the first row, and itemdatabound is called to bind the first row, that is, itemcreated and itemdatabound are executed alternately.
When the page returns, the itemcreated event will also be executed. Before page_load, The itemdatabound event will not be executed at this time.
Therefore, if you want to dynamically add controls to the DataGrid, you need to add them in the itemcreated event instead of in the itemdatabound event.

Case listitemtype. item:
Case listitemtype. alternatingitem:
System. Web. UI. webcontrols. imagebutton IMG = new imagebutton ();
IMG. commandname = "show ";
E. Item. cells [1]. Controls. Add (IMG );

Comparison of Three list controls:

DataGrid

Advantages: 1. Strong flexibility and rich built-in events

2. Provides paging, editing, sorting, and other features

3. Powerful DataGrid editor and template Columns

4. fast development and easy deployment

5. Table operations are very convenient.

6. Multiple built-in layout styles

Disadvantages: 1. Low performance, because each operation must be PostBack back to the server

2. Limited personalized output data (only HTML tables can be output)

Scope of use: It is mainly used in tables containing data. Generally, the data source is a dataset. Select the DataGrid for sorting, paging, multi-column display, and performance requirements.

Datalist

Advantages: 1. Powerful template features and high flexibility

2. Data editing status is supported.

3. better performance than DataGrid

Disadvantages: 1. the development cycle is slightly higher than that of the DataGrid.

2. No DataGrid Editor

3. It is not easy to implement paging and sorting functions

Scope of use: Mainly used for single-column data lists, high-performance custom data tables, multiple records per line, such as electronic album (including pagination)

Repeater

Advantages and disadvantages: 1. the control is completely HTML-based and more personalized

2. pagination, editing, and sorting are not supported.

3. The longest development cycle

4. The default style is not provided and must be edited manually.

5. The best performance, but the least features

Scope of use: Mainly used for data presentation with higher flexibility and performance.

DataGrid Overview:

A DataGrid is similar to a database table. A record set consists of an items and a columns. A row set consists of multiple ddcolumns and a column set consists of multiple datagriditems.

Working principle: 1. dataset obtains data; 2. Specify the data source of the DataGrid as dataset; 3. Bind data to the DataGrid. When binding data, the DataGrid column is automatically loaded. After creation, two events, itemcreated and itemdatabound, are called to create rows.

The DataGrid has two objects: datagridcolumn (representing a column) and datagriditem (representing a row ).

Each row has listitemtype, which has the following types: Header, footer, item, alernatingitem, selecteditem, edititem, separastor, and pager.

A column set can be of the following types: boundcolumn, hyperlinkcolumn, buttoncolumn, and templatecolumn.

If the DataGrid has a child control, the DataGrid obtains the control through the itemcommand event.

Description of datagridcolumn:

1. Bind Column: boundcolumn. The text field is displayed in standard mode. When it is in editing status, it is displayed as textbox.

2. button column: includes the select button, delete button, update button, edit button, and common button. Each button has two types of events. button style, linkbutton and Pushbutton

3. hyperlink Column

4. template column: templatecolumn, which has full control over the controls displayed to users. It can be divided into multiple templates, including headertemplate, itemtemplate, editiitemtemplate, and footertemplate. Non-template columns can be converted to template columns to provide more flexible functions.

5. Edit command Columns

The preceding columns are inherited from the datagridcolumn.

Example: 1. Drag and Drop a DataGrid Control on the page

2. Drag and Drop a sqldataadapter

3. Generate a dataset

4. Configure the DataGrid attribute, configure the data source, data members, and data key fields (by which primary key is bound), configure columns, and generate customized columns in the order of auto-generated columns.

5. write code in the page_load event

If (! Page. ispostback)

{

Sqldataadapter1.fill (dscustomers1 );

Datagrid1.databind ();

}

6. Add edit, update, cancel, and delete buttons to write events for these buttons

Void binddata ()

{

Sqldataadapter1.fill (dscustomers1 );

Datagrid1.databind ();

}

Private void datagrid1_editcommand (Object source, system. Web. UI. webcontrols. datagridcommandeventargs E)

{

Datagrid1.edititemindex = E. Item. itemindex; // sets the editing status of the current behavior.

Binddata ();

}

Private void datagrid1_updatecommand (Object source, system. Web. UI. webcontrols. datagridcommandeventargs E)

{

// Obtain each field in the row first

String customerid = E. Item. cells [1]. Text; // unedited

String companyName = (textbox) E. Item. cells [2]. controls [0]). Text; // edit the status

String contactname = (textbox) E. Item. cells [3]. controls [0]). text;

String contacttitle = (textbox) E. Item. cells [4]. controls [0]). text;

String address = (textbox) E. Item. cells [5]. controls [0]). text;

String city = (textbox) E. Item. cells [6]. controls [0]). text;

String region = (textbox) E. Item. cells [7]. controls [0]). text;

String Country = (textbox) E. Item. cells [8]. controls [0]). text;

Sqldataadapter1.fill (dscustomers1); // refill the dataset

Dscustomers. customersrow DR = dscustomers1.mers MERs. findbycustomerid (customerid); // get the current row

// Obtain the modified value

Dr. companyName = companyName;

Dr. contactname = contactname;

Dr. contacttitle = contacttitle;

Dr. Address = address;

Dr. region = region;

Dr. Country = Country;

Sqldataadapter1.update (dscustomers1); // update a dataset

Dscustomers1.acceptchanges (); // update accepted

Datagrid1.edititemindex =-1; // The status is not editable.

Binddata (); // rebind data

}

Private void datagrid1_deletecommand (Object source, system. Web. UI. webcontrols. datagridcommandeventargs E)

{

String customerid = E. Item. cells [1]. Text; // obtain the primary key of this row.

Sqldataadapter1.fill (dscustomers1); // refill the dataset

Dscustomers. customersrow DR = dscustomers1.mers MERs. findbycustomerid (customerid); // get the current row

Dr. Delete (); // delete a row

Sqldataadapter1.update (dscustomers1); // update a dataset

Dscustomers1.acceptchanges (); // update accepted

Binddata (); // rebind

}

Private void datagrid1_cancelcommand (Object source, system. Web. UI. webcontrols. datagridcommandeventargs E)

{

Datagrid1.edititemindex =-1;

Binddata ();

}

Precautions for using the DataGrid:

1. We recommend that you do not use auto-generated columns for greater flexibility.

2. If a column is automatically generated and specified in the DataGrid, the repeated settings of the column are obtained. The system displays the columns that are specifically declared, followed by all automatically generated columns.

3. Do not use only the control ID to reference the control in the DataGrid project. Use findcontrol to specify the control.

Description

Note:

For non-template columns: datagriditem. cells [cell number]. controls [control number] subscript starts from 0. It can be converted into corresponding controls, such as boundcolumn: Label editcolumn: textbox linkcolumn: datagridlinkbutton.

When the template column is selected, the index of control must be added with 1 because control [0] literalcontrol = "";

Suggestion: When you know the Control ID value, we recommend that you use datagriditem. findcontrol ["Control name"] to obtain

The process of creating a row using the datagriditem: When the row can be paged, The itemcreated event is created in sequence (if there is a paging) Pager (header page), header (header), item (one row ), alternatingitem (alternate row), footer (footer), and pager (if any ). If you press the "edit" button, execute the edititem of the row in which the current edit button is located. If you press the select button, execute the selecteditem of the row in which the current select button is located.

The process for triggering the DataGrid binding event:

1. If the databind method is executed to bind a column, this method is immediately triggered.

2. itemcreated creates a row (row container) and can be converted to datarowview.

3. <% # expression %> On the page. ASPX page

4. The itemdatabound binds row data and stores the data in the row container (Data Binding), which can be converted to datarowview.

5. Add the Count attribute to the items set + 1, repeat the 2-5 Process

6. After the data is loaded, the prerender data is displayed.

Note: If you manually add a custom control during creation (without using a template column), you must bind it to the itemcreated event.

FAQs about DataGrid binding events:

1. When E. Item. dataitem is referenced, the error "the object cannot be null" is returned"

Cause: the row type is not determined under itemcreated or itemdatabound. (datarowview) (E. Item. dataitem) values are available only under item, alternatingitem, selecteditem, and edititem.

2. You can use datagriditem to search for how to access a row of data after data access. The code structure is as follows:

Foreach (maid ){

}

Do not use DGI. datagriditem for access, because it is null again after itembound.

Note when using itemcreated: when loading, modifying the row attribute or the control attribute in the row, you should judge the itemtype, because each cell has a different display mode of the item type.

Data Binding: the ASP. NET data binding syntax is only calculated when the databind method is called. The called variable must be declared as public.

Simple attribute: <% # custid %>. For example, if code behind declares a variable and needs to be displayed on the interface

Set: <asp: ListBox id = "list1" datasource = '<% # myarray %> 'runat = "server"/>

Expression: <% # (customer. fistname + "" + customer. lastname) %>

Method Result <% # getbalance (custid) %>

Data Binding of template Columns

Container. dataitem container method:

Dataitem refers to a row of the DataGrid. You can convert the data type to datarowview and obtain each unit in the row. That is, the functions of the datagriditem and container. dataitem are the same.

Method 1: cyclically retrieve the column name in the bound DataGrid as mermerid

Method 2: Obtain the customerid (itemdatabound event) during data binding to the DataGrid. dataitem is only applicable to data items in the DataGrid control. That is, listitemtype must be item, alternatingitem, selecteditem, or edititem, therefore, you must add judgment .)

Method 3: databinder .. <% # Databinder. (name container of the data item, data field name, Format String) %> for the named container of DataGrid, datalist, repeater: container. dataitem. Disadvantage: low performance.

Itemcommand event

The event of the Child control in the template column-"bubble event ". The subcontrol calls the itemcommand event and specifies the commandname of the control to call the subcontrol Event code.

Personalized paging tips: by default, only numbers are supported. You can modify the default display in itemcreated event itemtype = listitemtype. pager.

Instance 1: Use of template columns. Dropdownlist is used in field editing mode. Steps:

1. Drag and Drop a DataGrid Control on the interface.

2. Drag and Drop a sqldataadapter control, set sqlconnection, and generate a dataset.

3. Set this column as a template Column

4. Add item and edititem, bind a field in container. dataitem to the item, place dropdownlist in edititem, and bind fieldname and fieldvalue

5. Fill in the itemdatabound event of the DataGrid and bind the dataset to be bound to the dropdownlist. Note: Before binding, determine the item type. E. Item. itemtype = listitemtype. edititem

6. modify the update value of the updataitem event in the drop-down list. Note that you must set the ID of the drop-down list in advance and use the findcontrol method to obtain it. The index of the control must be added with 1, because control [0] literalcontrol = "".

Instance 2: Use of the itemcommand event. Click a value in the drop-down list to display the selected item in the upper part of the page.

1. Define the name of the subevent to be processed in the selectedvaluechanged event attribute of dropdownlist.

2. Define the subevent function in the background code. Note that the event attribute should be public. Otherwise, it cannot be displayed on the foreground.

Example 3: test the binding process of a column

1. Add a button to the page

2. Click Add button to display all generated row types added to the string.

3. In the itemcreated event, add the attributes of each generated row to the string.

Instance 4: Insert a row. Principle: The new row is displayed in the footer of the DataGrid.

1. Add a button to the page

2. Add a button event and execute datagrid1.showfooter = true;

3. In itemcreater, when the type is footer, it rounds through each cell, sets the control to be placed, and adds the event processing name and display text to the control.

4. Add a processing method for each commandname in the itemcommand event of the DataGrid. For example, for an insert event, you need to add a new record and set the showfooter attribute to false. to cancel an insert event, you only need to set the showfooter attribute to false.

 

 

I use the DataGrid to display the list and want to provide the function of selecting data in a column.
Therefore, I edited a template column and added a dropdownlist control to the itemtemplate, but the event Code cannot be edited.
Setting dropdownlist to autopostback does not produce itemcommand events.

Private void maid (Object sender, system. Web. UI. webcontrols. datagriditemeventargs E)
{
If (E. Item. itemtype = listitemtype. Item | E. Item. itemtype = listitemtype. alternatingitem)
{
// Assume that the first column contains the SS dropdownlist
Dropdownlist progress = E. Item. cells [0]. findcontrol ("progress") as dropdownlist;

Progress. selectedindexchanged + = new system. eventhandler (this. dropdownlist+selectedindexchanged );
}
}

 

 

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.