Asp. NET Web DataGrid usage Guide

Source: Internet
Author: User

Datagrid/datalist is very important in ASP, where data of table type is displayed, most of these controls are used.

First, the method

1, DataBind
Very simple, the most common method. Bind data with. There is only one point to note: After this method is executed, the DataGrid (because the DataGrid and DataList are very similar, so the following description is for the DataGrid, but not far from the DataList) inside all the controls that display the bound data, will display the data in the DataSource, and the rest of the controls will be initialized to the state of the. aspx design.

Second, the attribute

1, DataSource
Where there is databind, there should be datasource. If you do not specify DataSource and execute DataBind, the DataGrid will not show anything.
DataSource are generally datasets, DataTable, or DataView. Of course, you can also bind DataReader or other classes that implement IEnumerable.

2, Datakeyfield,datakeys
Once you've positioned a row in the DataGrid, you'll want to know where the row is in the data table, there are at least five ways to do this, and setting the DataGrid's DataKeyField is one of those methods.
DataKeyField is generally set to the unique field of the datasheet (otherwise meaningless), and the value of the key field corresponding to this line can be obtained by DataKey.
DataKeys is a collection of datakey that reads the datakey of the corresponding row through the row's index.

3, Edititemindex,selectedindex,currentpageindex,selecteditem
These properties are well understood, the name will know what the meaning, it should be noted that after setting up the EditItemIndex or CurrentPageIndex need to re-execute the DataBind method (of course, as mentioned earlier, also need to set DataSource).

4, Columns
There's nothing to explain, columns is columns, a collection of columns that can set the properties of a column, including visible, HeaderText, Footertext, SortExpression, and so on.
Serious note: Auto-generated columns are not included in columns. The columns that are added in the code are only included in the. aspx display of the declared columns.

5. Items
As the saying goes, the last is the most important, the items as the last attribute to introduce, formally based on such reasons.
Items is a collection of datagriditem that can traverse the DataGridItem of the data displayed in the current DataGrid.
5.1, DataGridItem
Each DataGridItem is a row displayed in the DataGrid, which includes:
Header section of the header DataGrid control
Item in the Item DataGrid control
AlternatingItem alternating items in a DataGrid control
SelectedItem the selected item in the DataGrid control (set by SelectedIndex, read by SelectedItem property or Items[selectedindex])
EditItem an item in the DataGrid control that is in edit state (set by EditItemIndex and read by Items[edititemindex])
Separator separator between items in a DataGrid control
Footer the footnote portion of the DataGrid control
Pager page Selection section of the DataGrid control
Note that the Items property of the DataGrid does not include headers, Footer, pager, DataGridItem.
Properties of 5.1.1, DataGridItem
itemindex--get the index of rows in items
itemtype--returns the type of the row, which is the header listed above, Item 、...、 Pager
cells--returns all the TableCell that the row contains (whether it is a declared or auto-generated, whether visible or hidden), and through TableCell, you can read the text displayed in the cell, the contained controls
Serious Note: only BoundColumn columns and auto-generated columns are allowed to read the displayed text through the Tablecell.text property. HyperLinkColumn, ButtonColumn, and editcommandcolumn all need to convert the target control to the appropriate control.
Like what:
Suppose the first column of the DataGrid is declared as follows
<asp:hyperlinkcolumn datatextfield= "au_id" headertext= "au_id" datanavigateurlfield= "au_id" datanavigateurlformatstring= "Edit.aspx?id={0}" ></asp:HyperLinkColumn>
When reading, you can use:
Items[0] Represents the first row, Cells[0] represents the first column, Controls[0] represents the first control in the cell (and only this control can be used)
HyperLink link = (HyperLink) datagrid1.items[0]. Cells[0]. Controls[0]);
Response.Write (link. Text);
As for the template column (TemplateColumn), of course, can also be passed datagrid1.items.cells[j]. Controls[n] to get and then convert to the original control type, but there is a better way to find the control with FindControl.
FindControl is a System.Web.UI.Control method that can find child controls based on the child control ID
Like what:
Suppose a column of the DataGrid is declared as follows
<asp:TemplateColumn>
<ItemTemplate>
<asp:textbox runat= "Server" id= "txtID" text=<%# DataBinder.Eval (Container.DataItem, "au_id")%>>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
Read method:
TextBox txt = (textbox) datagrid1.items[1]. FindControl ("txtID");
Response.Write (txt. Text);
Note: There is no cell in the DataList.

III. Events

1, ItemCommand, CancelCommand, DeleteCommand, EditCommand, UpdateCommand
In the DataGrid, the events executed after clicking Button, LinkButton, and the event that is executed depends on the commandname of the button. In fact, the main one is ItemCommand, and the back four are just a small part of ItemCommand,
For example, the commandname of a button is "Cancel", when it returns, the first thing to do is the ItemCommand event, then the CancelCommand event.

2, PageIndexChanged
If your DataGrid is paged, this event is triggered when you click 1, 2, 3, or < > on pager on the DataGrid.
In this event, you can use E. NewPageIndex to read the page to be changed and assign it to the DataGrid's CurrentPageIndex property, and finally, do not forget to set DataSource, but also to execute DataBind.
Note: DataList does not have this event, if you need to DataList in the page, you can read the data for a period of time, and then bind the data of the current segment to DataList.

3, itemdatabound,itemcreated
The first thing to say is the time of occurrence of these two events.
ItemDataBound, as long as the DataBind method is executed, the event will be fired immediately.
itemcreated, if the page is the first access (Page.IsPostBack = False), the first time the DataBind is executed, the ItemCreated event is fired first, that is, after the DataBind is executed, First the header line is created with itemcreated, then the header line is bound with ItemDataBound, then the first row is created with itemcreated, and then ItemDataBound is used to bind the first row, This means that itemcreated and itemdatabound are alternately executed.
ItemCreated is also executed when the page is returned
Event, before Page_Load, but this time no longer executes the ItemDataBound event.
So, if you want to add a control dynamically in the DataGrid, it needs to be in the ItemCreated event, not in the ItemDataBound event.

Iv. Code Snippets

1, the DataGrid display double-sided table head
Assuming that your DataGrid has three columns, and now you want to use the first two columns as "big Class 1" and the third column as "Big Class 2", you can now add the following code to the ItemDataBound event:
if (E.item.itemtype = = Listitemtype.header)
{
E.item.cells[0]. ColumnSpan = 2;
E.item.cells[0]. Text = "Large class 1</td><td> Large class 2</td></tr><tr><td>" + E.item.cells[0]. Text;
}
This method allows you to add new rows for any purpose.

2. Set the width of the edit box for bound columns or automatically generated columns
Please include the code in your ItemDataBound event:
if (E.item.itemtype = = ListItemType.EditItem)
{
for (int i = 0; i < E.item.cells.count; i++)
{
TextBox txt = (textbox) e.item.cells.controls[0];
Txt. Width = Unit.pixel (50);
}
}

3. Handling DropDownList events in the DataGrid
The DropDownList does not have a commandname attribute, so the ItemCommand event cannot be used, but you can try it this way:
The DropDownList control that is added to the template column of the DataGrid
<asp:dropdownlist runat= "Server" id= "DDL" autopostback= "True" onselectedindexchanged= "ddl_selectedindexchanged" />
Then you add a function to the. aspx.cs
protected void Ddl_selectedindexchanged (object sender, System.EventArgs e)//must be declared as protected or public and cannot be private.
{
You can add other code here
}

3.1, how to get the value of the other cell in the above event?
We know that the DataGrid is completely a table-structured control, the DataGrid contains DataGridItem, and each datagriditem contains TableCell, so we can have a control in TableCell, Using the control's parent to get TableCell, and then using TableCell's parent, you can get DataGridItem.
protected void Ddl_selectedindexchanged (object sender, System.EventArgs e)//must be declared as protected or public and cannot be private.
{
DropDownList DDL = (DropDownList) sender;
TableCell cell = (TableCell) DDL. Parent;
DataGridItem item = (DataGridItem) cell. Parent;
Response.Write (item. Cells[0]. Text);
}

4. How to get the control in header, Footer, pager
Method one: In ItemCreated or ItemDataBound, the specific code is not to write more
Method Two: Traverse the DataGrid for all item (note that it is not traversing the item under Datagrid1.items)
foreach (DataGridItem item in Datagrid1.controls[0]. Controls)
{
if (item. ItemType = = Listitemtype.header)
{
With item. FindControl find the appropriate control
}
}
You may notice that there is a datagrid1.controls[0]. controls, which means that, under DATAGRID1, there is a child control, this child control is the datagridtable type, he is below the DataGridItem collection
In DataList, the following child controls are directly datalistitem, without table:
foreach (DataListItem item in Datalist1.controls)
{
//....
}

Asp. NET Web DataGrid usage Guide

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.