Asp. DataGrid Common errors in net

Source: Internet
Author: User
Tags contains sort unique id knowledge base visual studio
Asp.net|datagrid| Error Summary: Learn how to avoid some common errors that might occur when you use the ASP.net DataGrid control for development.
is the Datagrid control Microsoft? One of the most powerful and widely used WEB controls in asp.net has been recognized by ASP.net authorities. Although the Datagrid control is easy to use, it is also easy to create trouble for users. Here are some of the mistakes made by many people, from beginners to experienced. NET experts. You can see that many distressed users ask questions about these errors in the ASP.net newsgroups and forums. Follow the fairly simple steps outlined in this article to help you avoid these errors and save a lot of development time.

You can use the Datagrid to create list data without using the

I know you will no longer use the code shown below, but many of the old-fashioned users in the ASP.net field continue to use 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>")

The above code can be simplified so that it is only:

<asp:datagrid runat= "Server" datasource= "MyDataReader"/>

and called. DataBind () method. Even if you need special control over HTML output, you can use a data Web control when the contents of the recordset are repeated on the user interface.

Forget to check IsPostBack in the Page_Load event

One of the most common errors is forgetting to check the IsPostBack condition of the page before the data is bound. For example, when the Datagrid is in edit mode, ignoring the check will cause the edited value to be overwritten by the original value in the data source. However, there is at least one major exception to this rule, please refer to the continued use of large ViewState.

The following is a typical Page_Load event that contains a IsPostBack check. Bindgrid () is a routine that imports and sets the data source for the Datagrid and calls the DataBind () method.

Sub Page_Load
If not IsPostBack Then
Bindgrid ()
End If
End Sub

When you need more flexibility, you still insist on using automatically generated columns

If the DataGrid is in an environment that requires any particular format, or if you need to use any other Web control in the DataGrid, you must turn off AutoGenerateColumns. Keeping the setting of the AutoGenerateColumns property to "True" (the default setting) is valid only in the simplest Datagrid scenario. But for almost any actual application, you must set this property to "False" and specify the column explicitly in the <columns></columns> section of the Datagrid declaration. Microsoft Visual Studio?. NET users can create these columns graphically by using the Property Builder.

Note: If you leave the AutoGenerateColumns setting to "True" and you specify a column in the <columns> section of the Datagrid, you will end up with a duplicate setting for the column. The system will first display the specially declared columns, followed by all auto-generated columns.

Try to refer to a control in the Datagrid project using only the control ID

Many people do not realize that for controls in the ItemTemplate under the TemplateColumn of a Datagrid (such as a TextBox control with a "MyTextBox" ID), they cannot be in the following code or in the ASPX page <script The > section invokes the control directly using the code shown below:

Dim myvalue as String = Mytextbox.text

The code will cause a terrible "name ' MyTextBox ' no Declaration" error.

Because the Datagrid is made up of multiple rows (projects), each row in the data source actually has a separate "MyTextBox" instance. asp.net precede each control's ID with the ID of each named container in the control hierarchy, so that the Textbox will have a unique ID that is different from the IDs of all the other controls on the page. For example, if MyTextBox is in DataGrid1, the generated ID will be datagrid1:_ctl2:mytextbox. "_ctl2" represents the current line where MyTextBox is. The IDs of other MyTextBox instances on the page may be Datagrid1:_ctl3:mytextbox, Datagrid1:_ctl4:mytextbox, and so on. To retrieve the "MyTextBox" value you want to find, you need to call the FindControl method on the appropriate datagriditem. The DataGridItem is used as the parent naming container for the 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

Calling CType on the result of the FindControl call will cast the return value from the Object type to the TextBox type for access. The Text property.

Forgotten to execute in each Datagrid event. DataBind () call, which causes the postback

A common problem is: "When I click on the edit link in a row of a Datagrid, the page is postback and contains no data." What's wrong with that? "The problem is that the data is bound to the grid only the first time the page is invoked. In each DataGrid event (Edit, Update, Cancel, Page, or Sort), make sure that the Datasource property of the DataGrid is set (unless you are already in the <asp:Datagrid> Declaration, and calls the DataBind () method on the Datagrid.

Runtime unnecessarily dynamically creating a DataGrid control or column in a DataGrid

In some business and technical scenarios, it is necessary and perfectly appropriate to create ASP.net controls at run time. For example, sometimes you need to select a different page option before you can determine the user interface at run time. Or, to create a composite server control, each of these child controls needs to be created dynamically because these child controls cannot be created declaratively. If you are experiencing these situations, be aware that you do not retain these dynamic controls when submitting pages. Dynamic controls (for example, in the Page_Init event) must be re-created at each postback, early in the page life cycle. Warning: Create a control early, create a control to be diligent. For more information about how to create controls dynamically, see Microsoft knowledge Base article how to:dynamically Create Controls in asp.net with Visual Basic. NET.

However, if you do not need to dynamically create controls in the Datagrid application, avoid using the technology to avoid problems. Although it is possible to create dynamic Datagrid, they can cause a variety of events, which are often frustrating. In other words, do not dynamically create controls to avoid the creation of controls that make ASPX files fragmented.

Continuous use of large ViewState

The Datagrid control adds a lot of ViewState to the page, which is annoying because it causes a sharp increase in the overall size of the page that is presented to the user. The easiest way to keep the page size from growing is to disable ViewState for the entire page, or for specific controls alone. For example, if a page does not generate a postback, it is safe to disable ViewState for the entire page. Otherwise, disable ViewState for each control whose state information does not change between two postbacks, or disable ViewState for those controls that do not need hidden fields to track their state.

When you disable ViewState for a DataGrid control or a page that contains a DataGrid, you need to perform some special steps if the DataGrid initiates a postback event. First, you must rebind the Datagrid in Page_Load on each postback. This is contrary to the usual practice (and the description in the second question above). However, if you disable ViewState, this step is required so that other Datagrid events can be raised correctly after the Page_Load is executed. If you want to handle any part (or all) of the following DataGrid events, you will also need to manually store some of the DataGrid properties in ViewState. For example, if you are editing in a DataGrid that is disabled for ViewState, as long as you store the EditItemIndex before the DataGrid is first bound in Page_Load, and the DataGrid is in edit mode, you can simply edititemin Dex's saving up to ViewState is enough.

Table 1:datagrid events and ViewState dependencies
Does the event depend on ViewState? fields to store in ViewState
ItemCreated No
ItemDataBound No
SortCommand is sortexpression.
EditCommand is EditItemIndex.
PageIndexChanged is CurrentPageIndex.
SelectedIndexChanged No


Listing 1: Example code that enables editing, sorting, and paging, but disables ViewState's Datagrid.

Sub Page_Load
If not ViewState ("EditItemIndex") are nothing Then
Datagrid1.edititemindex = ViewState ("EditItemIndex")
End If
If not ViewState ("CurrentPageIndex") are 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 Datagrid1_sortcommand (s as Object, E as DataGridSortCommandEventArgs)
ViewState ("sortexpression") = E.sortexpression
Bindgrid ()
End Sub

Sub Datagrid1_editcommand (s as Object, E as DataGridCommandEventArgs)
Datagrid1.edititemindex = E.item.itemindex
ViewState ("edititemindex") = E.item.itemindex
Bindgrid ()
End Sub

Sub datagrid1_pageindexchanged (s as Object, E as DataGridPageChangedEventArgs)
Datagrid1.currentpageindex = E.newpageindex
ViewState ("currentpageindex") = E.newpageindex
Bindgrid ()
End Sub

When using ItemDataBound or itemcreated events, forget to check the appropriate ListItemType

The Datagrid control raises two events for each data row. The first time you add each row to the Datagrid, a itemcreated event is raised, and the ItemDataBound event is raised when the data is bound to each row. When you add cells to the table output of a 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 range of values. The key, however, is to keep in mind that these events are raised for all Datagrid project types, including headers, footers, and pager items. If the project type is not carefully checked before the data is referenced during the ItemDataBound event, the first item (usually the header row) will have an error. If the Datagrid has paging enabled and is set to appear at the top, the first item becomes a paging program project. The following sample code shows how to make the correct listitemtype check before referencing the project data. Don't forget alternatingitem!.

Sub Datagrid1_itemdatabound (source as object,e as DataGridItemEventArgs)
If (E.item.itemtype = listitemtype.item Or e.item.itemtype = listitemtype.alternatingitem) Then
If e.Item.DataItem ("Forumdate"), Datetime.today Then
E.item.cells (1). BackColor =system.drawing.color.fromname ("#ffccff")
End If
End If
End Sub


Excessive use of the Datagrid (Repeater may be a better choice) when more control is needed on the generated HTML

If lazy programmers like the DataGrid controls (because the DataGrid controls do a lot of work for them), then programmers with a strong control desire must love Repeater controls. If you need or want to fully control all of the HTML that you create, use the Repeater control, which can help you complete the task. The Repeater control also has a slight performance advantage because it does not occupy system resources like all the built-in features of the Datagrid control. You can also consider using a compromised DataList control, which has the ability to edit and sort, and also to display records repeatedly on a single line.



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.