ASP. NET 3.5 core programming learning notes (24): DataGrid Control

Source: Internet
Author: User

The notable features of the DataGrid control are the columns and items set attributes, style and Data Binding attributes. The items attribute returns the set of the datagriditem object. Each element corresponds to the displayed row. The datagriditem class is a subclass of the tablerow class and is refined.

The output of the initird control consists of several elements: Header, item, alternating item, footer, and pager ).

The datakeyfield attribute provides the primary key fields of the underlying data source, and the datakeys set attribute provides the primary key values of each row. The datakeys set is automatically filled Based on the datakeyfield attribute value and the bound data source.

The cancelcommand and updatecommand events are triggered only when an item is in the editing status. The cancelcommand event corresponds to the event notification that the user clicks the "cancel" button. The updatecommand event corresponds to the event notification that the user saves all changes.

The DataGrid control consists of columns that can be bound to data. By default, the view of the control contains all fields in the data source. To automatically bind data, set the autogeneratecolumns attribute to false. In this case, only columns explicitly set in the columns set are displayed. The DataGrid supports multiple types of columns. The main difference is the data presentation form. If you manually add a column to the columns set, you must specify its type. If the automatic column generation function is enabled, all columns are of the boundcolumn type. The following table lists all column types supported by the DataGrid:

Note: The autogeneratecolumns attribute is not mutually exclusive with the columns set. If the former is set to true and the set is not empty, the grid control first displays all automatically generated columns, append the User-Defined column to the end.

Example:

<asp:datagrid runat="server" id="grid" ...>
...
<columns>
<asp:BoundColumn runat="server" DataField="employeeid" HeaderText="ID" />
<asp:BoundColumn runat="server" DataField="firstname" HeaderText="First Name" />
<asp:BoundColumn runat="server" DataField="lastname" HeaderText="Last Name" />
</columns>
</asp:datagrid>

The order of columns in the set determines the display sequence of columns in the DataGrid Control.

We can also add columns to the DataGrid Control by encoding:

BoundColumn bc = new BoundColumn();
bc.DataField = "firstname";
bc.HeaderText = "First Name";
grid.Columns.Add(bc);

The DataGrid does not save the content of the columns set to the view state, so it is always empty when it is just sent back. To save the dynamically added columns, we need to re-add these columns to the control after each sending.

Data Binding Column

All types of grid columns inherit from the datagridcolumn class. These types have some common attributes:

The key attributes for setting grid columns are datafield and dataformatstring. The former is used to specify the name of the bound column, and the latter is used to set the text display format. The readonly attribute takes effect only when the edited command column is added to the grid. This attribute determines whether the cells in the current column can switch to the editing mode.

The following code is inserted into two columns and the header text and source fields are specified respectively. In addition, a format string is specified for the second column to render it in currency format, and the text is set to right alignment:

<asp:boundcolumn runat="server" datafield="quantityperunit" headertext="Packaging" />
<asp:boundcolumn runat="server" datafield="unitprice" headertext="Price" DataFormatString="{0:c}" >
<itemstyle width="80px" horizontalaigh="right" />
</asp:boundcolumn>

The appearance of a column must be specified by a child style element.

Hyperlink Column)

In the column represented by the hyperlinkcolumn class, each cell contains a hyperlink. Datatextfield accepts the names of fields used to set the hyperlink text, and datanavigateurlfield accepts the URL Information. Another attribute is datanavigateurlformatstring, which defines the final format of the URL. Example:

<asp:hyperlinkcolumn runat="server" datatextfield="productname"
headertext="product"
datanavigateurlfield="productid"
datanavigateurlformatstring="productinfo.aspx?id={0}"
target="ProductView">
<itemstyle width="200px" />
</asp:hyperlinkcolumn>

All links point to the same page -- productinfo. aspx, but each link has a product ID.

Through the datanavigateurlfield and datanavigateurlformatstring attributes, we can make the URL of the hyperlink contain parameters. However, by default, only one parameter can be included, that is, the value bound to the datanavigateurlfield attribute. To bind a link to multiple parameters, we need to use the template column or the gridview control.

Button Column

The buttoncolumn class represents the button column. The button column differs from the hyperlink column in that all buttons are sent back to the same URL.

The button column is used to perform specific operations after you click a row of buttons. All buttons in this column are associated with a script code for sending back. After sending back, the itemcommand process on the server is executed. In this process, we can use the command name (commandname) to differentiate the click of buttons from different columns, and obtain the index of the row to be clicked through the itemindex attribute of the datagriditem class. The reference of the datagriditem object will be passed to the itemcommand event.

"Select column" is a special button column. The command name is select. After a column is clicked, The DataGrid automatically draws the selected row with a different style setting, which is specified by the selecteditemstyle attribute.

<asp:ButtonColumn runat="server" text="select" CommandName="Select" />

The style of the selected row is set by selecteditemstyle:

<selecteditemstyle backcolor="cyan" />

The selectedindexchanged event notifies you of changes to the selected item. However, before the event is triggered, the application can process related itemcommand events. When the program runs selectedindexchanged, you can use the selectedindex attribute to obtain the index of the newly selected row.

Template Column

The template column allows us to use HTML text and server controls to set the layout of such column cells. The control in the template column can be bound to any multiple fields of the data source. Specifically, we can bind multiple fields to an expression, and even use HTML attributes to modify the tags. Template columns are custom and cannot appear in automatically generated columns. To share multiple columns with the same template, we can only copy the code on the ASP. NET page.

The template column is marked with the <templatecolumn> label and is finally presented by the templatecolumn. The subject part of the tag can contain four different templates: itemtemplate, edititemtemplate, headertemplate, and footertemplate. The template column is not automatically bound to the data source field. To bind the template column to several data fields, you must use the data binding expression. Specifically, we can use the eval method to calculate the data binding expression at runtime, and the returned value is automatically converted to the type. Example:

<asp:templatecolumn runat="server" headertext="Last Name">
<itemtemplate>
<asp:label runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "lastname") %>' />
</itemtemplate>
</asp:templatecolumn>

Use of the DataGrid Control

Interactions between the DataGrid and the host page are limited to notifications in the form of sending back events. The DataGrid notifies the page of events, and other operations are determined by the page.

Paging

If the index of the current page is changed, the control will trigger the pageindexchanged event to the application. As follows:

Protected void grid_pageindexchanged (Object sender, datagridpagechangedeventargs E)
{
Grid. currentpageindex = E. newpageindex;
// You must reset the data source to force update the control.
Grid. performanceid = "sqlperformance1 ";
}

Note: We need to assign a value to the performanceid to trigger the internal data source change event so that the control can load the new dataset.

The DataGrid Control also supports custom pagination and only binds records suitable for the current display to the control:

Protected void grid_pageindexchanged (Object sender, datagridpagechangedeventargs E)
{
Grid. currentpageindex = E. newpageindex;
Grid. datasource = getrecordsinpage (grid. currentpageindex );
}

Protected object getrecordsinpage (INT pageindex)
{
// Obtain data on the specified page
...
}

Data Sorting

The allowsorting attribute of the DataGrid control is used to enable column sorting. After this function is enabled, you must process the sortcommand event handler. Otherwise, the handler will not work. Example:

protected void grid_SortCommand(object sender, DataGridSortCommandEventArgs e)
{
SqlDataSource1.SelectCommand += " Order by " + e.SortExpresstion;
grid.DataSourceID = "SqlDataSource1";
}

Edit Existing records

The key object involved in local editing is editcommandcolumn. This type of column adds a special link to all rows in the grid. After a link is clicked, the host page returns and the corresponding lines are drawn in editing mode.

To complete the DataGrid editing operation, you must write three Event Handlers: Use the editcommand event to switch the editing mode of the mesh and use cancelcommand to switch the mesh back to the read-only mode, use updatecommand to save updates and refresh the grid content.

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.