Common DataGrid errors

Source: Internet
Author: User
Address: http://www.microsoft.com/china/msdn/library/dnaspp/html/aspnet-commondatagridmistakes.asp

Abstract: learn how to avoid some common errors that may occur when using the ASP. NET DataGrid Control for Development (this article contains links to English sites ).

Directory
You can use the DataGrid to create list data but not use it.
Forget to check ispostback in the page_load event
When more flexibility is required, you still need to use automatically generated columns.
Try to use only the control ID to reference the control in the DataGrid Project
Yes (or should) Use paging instead
Failed to execute. databind () in each DataGrid event, resulting in sending back
Dynamically create a DataGrid control or column in The DataGrid without any need during running
Continuous use of large viewstate
When you use the itemdatabound or itemcreated event, you forget to check the appropriate listitemtype.
When you need more control over the generated HTML, The DataGrid is used too much (repeater may be a better choice)
References

The DataGrid control is one of the most functional and widely used Web controls in Microsoft ASP. NET, which has been recognized by ASP. NET authorities. Although the DataGrid Control is easy to use, it is also easy for users. The following are some of the mistakes made by many people, including beginners and experienced. Net experts. You can see that many boring users raise questions about these errors in ASP. NET news groups and forums. Following the simple steps outlined in this Article can help you avoid these errors and save a lot of development time.

You can use the DataGrid to create list data but not use it.
I know that you will not useCodeHowever, many conservative users in the ASP. NET field are still using them:

Response. Write ("<Table> ")
While mydatareader. Read ()
Response. Write ("<tr> ")
Response. Write ("<TD> ")
Response. Write (mydatareader (0 ))
Response. Write ("</TD> ")
Response. Write ("</tr> ")
Loop
Response. Write ("</table> ")

You can simplify the above Code so that it is only:

<Asp: DataGrid runat = "server" datasource = "mydatareader"/> and call the. databind () method. Even if you need special control over HTML output, you can use a Data web control when the content of the record set appears repeatedly on the user interface.

Forget to check ispostback in the page_load event
One of the most common errors is that you forget to check the ispostback condition of the page before binding data. For example, if the DataGrid is in "edit" mode, ignoring this check will overwrite the edited value in the data source. However, this rule has at least one major exception. For more information, see continue to use large viewstate.

The following is a typical page_load event that includes the ispostback check. Bindgrid () is a routine used to import and set the data source of the DataGrid and call the databind () method.

Sub page_load
If not ispostback then
Bindgrid ()
End if
End sub

When more flexibility is required, you still need to use automatically generated columns.
If the DataGrid environment requires any special format, or you need to use any other Web Control in the DataGrid, you must disable autogeneratecolumns. The autogeneratecolumns attribute is set to "true" (default), which is only valid in the simplest DataGrid solution. But for almost all practical applicationsProgramYou must set this attribute to "false" and specify columns explicitly in the <columns> </columns> section declared by the DataGrid. Microsoft Visual Studio. Net users can use the property generator to create these columns graphically.

NOTE: If autogeneratecolumns is set to "true" and the column is specified in the <columns> segment of 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.
Try to use only the control ID to reference the control in the DataGrid Project
Many people do not realize that for the controls in itemtemplate under the templatecolumn of the DataGrid (for example, Textbox Control with "mytextbox" ID ), you cannot directly call the control using the following code in the following code or in the <SCRIPT> section of the ASPX page:

Dim myvalue as string = mytextbox. Text

This code will cause a terrible "name 'mytextbox 'is not declared" error.

Because the DataGrid is composed of multiple rows (projects), each row of the data source actually has a separate "mytextbox" instance. ASP.. net adds the ID of each named container in the control hierarchy before the ID of each control, so that the textbox has a unique ID, which is different from the IDs of all other controls on the page. For example, if mytextbox is in datagrid1, the generated ID is datagrid1: _ ctl2: mytextbox. "_ Ctl2" indicates the current row of mytextbox. The IDS of other mytextbox instances on the page may be datagrid1: _ ctl3: mytextbox, and datagrid1: _ ctl4: mytextbox. To retrieve the "mytextbox" value to be searched, you need to call the findcontrol method for the appropriate datagriditem. This datagriditem is used as the parent naming container of textbox.

HTML:

<Asp: DataGrid runat = "server" id = "datagrid1">
<Columns>
<Asp: templatecolumn>
<Itemtemplate>
<Asp: textbox runat = "server" id = "mytextbox"/>
</Itemtemplate>
</ASP: templatecolumn>
</Columns>

Code:

Sub datagrid1_updatecommand (sender as object ,_
E As datagridcommandeventargs)
Dim myvalue as string = _
Ctype (E. Item. findcontrol ("mytextbox"), textbox). Text
'Perform operations on myvalue'
End sub

If you call ctype for findcontrol results, the return value is forcibly converted from the object type to the textbox type to access the. Text attribute.

Yes (or should) Use paging instead
Users may not want to scroll through thousands of records on a single page. Make sure that your application is properly designed to handle situations that may return a large number of records. For information about how to implement paging in the DataGrid, see paging in datagrid Quickstart tutorial. At Scott Mitchell'sArticleCreating a pageable, sortable DataGrid can find more information.

Failed to execute. databind () in each DataGrid event, resulting in sending back
A common problem is: "When I click the edit link in a row of the DataGrid, the page is sent back without any data. What is the error ?" The problem is that the data is only bound to the grid when the page is called for the first time. In each DataGrid event (edit, update, cancel, page, or sort), make sure that the datasource attribute of the DataGrid is set (unless it is already in the <asp: dataGrid> sets in Declaration), and calls the databind () method for the DataGrid.

Dynamically create a DataGrid control or column in The DataGrid without any need during running
In some business and technical solutions, creating ASP. NET controls at runtime is necessary and appropriate. For example, you can determine the user interface at runtime only after selecting other page options. Or create a composite Server Control. Each of the child controls must be dynamically created because they cannot be created in a declared manner. Note that these dynamic controls are not retained when you submit the page. A dynamic control (for example, in the page_init event) must be re-created at each sending back at an early stage of the page lifecycle ). Warning: it takes an early time to create controls, while creating controls must be diligent. For details about how to dynamically create controls, see Microsoft Knowledge Base Article how to: dynamically create controls in ASP. NET with Visual Basic. net.

However, if the DataGrid application does not need to dynamically create controls, do not use this technology to avoid trouble. Although dynamic DataGrid may be created, they can cause various events, which is usually a headache. In other words, do not dynamically create controls to prevent aspx files from being dispersed by creating controls.

Continuous use of large viewstate
The DataGrid Control adds a large number of viewstates to the page, which is annoying because it causes a sharp increase in the overall size of the page presented to the user. To make the page size not increase, the simplest way is to disable viewstate for the entire page or for some specific controls separately. For example, it is safe to disable viewstate for the whole page if the page does not produce a sending back. Otherwise, disable viewstate for each control that does not change the status information between two rounds, or disable viewstate for those controls that do not need to hide fields to track their own status.

When you disable viewstate for the DataGrid control or page that contains the DataGrid, if the DataGrid starts the send-back event, you need to perform some special steps. First, you must re-bind the DataGrid in page_load at each sending. This is against the conventional practice (and the description in the second question above ). However, this step is required if viewstate is disabled, so that other DataGrid events can be correctly triggered after page_load is executed. If you want to process any part (or all) of the following DataGrid events, you also need to manually store some DataGrid properties in viewstate. For example, when editing a viewstate-disabled DataGrid, you only need to re-store edititemindex before binding the DataGrid to page_load for the first time, and the DataGrid is in editing mode, you only need to store edititemindex to viewstate (see sample code ).

Table 1: dependency between DataGrid events and viewstate

Does the event depend on viewstate? Fields to be stored in viewstate
Itemcreated none
Itemdatabound none
Sortcommand is sortexpression
Editcommand is edititemindex
Pageindexchanged is currentpageindex
Selectedindexchanged none

Listing 1: The sample code of the DataGrid that enables editing, sorting, and paging, but disables viewstate.

Sub page_load
If not viewstate ("edititemindex") is nothing then
Datagrid1.edititemindex = viewstate ("edititemindex ")
End if
If not viewstate ("currentpageindex") is nothing then
Datagrid1.currentpageindex = viewstate ("currentpageindex ")
End if
Bindgrid ()
End sub
Sub bindgrid ()
Dim DV as dataview
DV = getdatasource ()
DV. Sort = viewstate ("sortexpression ")
Datagrid1.datasource = dv
Datagrid1.databind ()
End sub
Sub maid sortcommand (S as object ,_
E As datagridsortcommandeventargs)
Viewstate ("sortexpression") = E. sortexpression
Bindgrid ()
End sub
Sub maid editcommand (S as object ,_
E As datagridcommandeventargs)
Datagrid1.edititemindex = E. Item. itemindex
Viewstate ("edititemindex") = E. Item. itemindex
Bindgrid ()
End sub
Sub maid pageindexchanged (S as object ,_
E As datagridpagechangedeventargs)
Datagrid1.currentpageindex = E. newpageindex
Viewstate ("currentpageindex") = E. newpageindex
Bindgrid ()
End sub

When you use the itemdatabound or itemcreated event, you forget to check the appropriate listitemtype.
The DataGrid Control raises two events for each row. When each row is added to the DataGrid for the first time, the itemcreated event is triggered. when data is bound to each row, the itemdatabound event is triggered. When adding cells to the table output of the DataGrid, these events can be used to control the appearance or content of each cell. For example, you can modify the background color of a cell based on the value range. But the key is to remember that these events are triggered for all DataGrid project types, including Header, footer, and paging Program projects. If the project type is not carefully checked before the project data is referenced during the execution of the itemdatabound event, the first project (usually the title line) will encounter an error. If the DataGrid enables pagination and sets it to display at the top, the first project becomes a paging program project. The following sample code shows how to perform a correct listitemtype check before referencing project data. Do not forget alternatingitem!

sub maid (source as object, _
E as maid)
If (E. item. itemtype = listitemtype. item or _
E. item. itemtype = listitemtype. alternatingitem) Then
If e. item. dataitem ("forumdate") E. item. cells (1 ). backcolor =
system. drawing. color. fromname ("# ffccff")
end if
end sub

when you need more control over the generated HTML, The DataGrid is used too much (repeater may be a better choice)
If the lazy programmer prefers the DataGrid Control (because the DataGrid Control has done a lot of work for them), the programmer with a strong desire to control the Repeater control must like it. If you need or want to have full control over all created HTML, use the Repeater control to help you complete this task. The Repeater control has a slightly higher performance because it does not occupy system resources as it does with all built-in functions of the DataGrid Control. You can also consider using the compromise datalist control, which provides the edit and sort functions, as well as the ability to repeatedly display records within a row.

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.