Understand the operation of the gridview through the manual Program

Source: Internet
Author: User
Starting from:

Meow is connected to ASP. net is from ASP. NET 2.0 (vs2005), and the control plane of the gridview also appeared from this time, with the help of datasouce, it makes our use very convenient. You just need to drag it and set it. The information can be displayed on the webpage through the gridview. However, as a result, it may take some time to develop a replica set, I still don't know how the gridview works (because the communication package is good ).

This article does not require datasource (sqldatasouce, objectdatasouce, accessdatasource ,...) under the circumstance, some operations of the gridview can be understood through the ADO access information and the various events of the gridview. In this article, Xiao meow will write a program that describes the functions of the gridview, such as information processing, editing, modification, division, sorting, and segmentation.

Zookeeper jobs:

This example is taken as an example, and the North China Data Warehouse is used as an example. You can use the most simple data table [region] as an example. When you are updating the database, you can change the connection string and table name partition by yourself.

Plane:

The layout is very simple, that is, to arrange a gridview, and then select a style (you can distinguish between the original colors ), in addition, a templete fields is added to place the "operation frequency, division, operation frequency, and cancellation" statement. In addition, a button is arranged for the first response. The related program names are as follows:

 

<Asp: Label id = "lblmsg" runat = "server" text = ""> </ASP: Label> <br/> <asp: button id = "button1" runat = "server" text = "button"/> <asp: gridview id = "gridview1" runat = "server" allowsorting = "true" backcolor = "white" bordercolor = "# e7e7ff" borderstyle = "NONE" borderwidth = "1px" cellpadding =" 3 "gridlines =" horizontal "allowpaging =" true "pagesize =" 3 "> <rowstyle backcolor =" # e7e7ff "forecolor =" # 4a3c8c "/> <columns> <SP: templatefield> <edititemtemplate> <asp: button id = "btnupdate" runat = "server" text = "strongswan" commandname = "Update"/> <asp: button id = "btncancel" runat = "server" text = "cancel" commandname = "cancel"/> </edititemtemplate> <itemtemplate> <asp: button id = "btnedit" runat = "server" text = "commandid" commandname = "edit"/> <asp: button id = "btndel" runat = "server" text = "except" commandname = "delete" onclientclick = "Return confirm ('Are you sure Do you want to collect other information ?? '); "/> </Itemtemplate> </ASP: templatefield </columns> <footerstyle backcolor = "# b5c7de" forecolor = "# 4a3c8c"/> <pagerstyle backcolor = "# e7e7ff" forecolor = "# 4a3c8c" horizontalalign = "Right "/> <selectedrowstyle backcolor =" # 738a9c "font-bold =" true "forecolor =" # f7f7f7 "/> 

Post-program resume:

Then, we will start to write the component of the Program program. First, you need to manually update the program. Of course, you need the namespance related to imports.

 
Imports system. dataimports system. Data. sqlclient

And set the connection string

 
Private connstr as string = "Data Source =. \ sqlexpress; initial catalog = northwind; Integrated Security = true"

Then create the [query, modify, and divide] data function to [retrieve, modify, and divide] the region data table, the function retrieved by the aggregate is returned to the datatable.

Private function getdata () as datatable dim dT as new datatable try using conn as new sqlconnection (connstr) dim sqltxt as string = "" sqltxt + = "select top 50 *" sqltxt + = "from [region] (nolock) "sqltxt + =" "dim cmd as new sqlcommand (sqltxt, Conn) dim da as new sqldataadapter (CMSD) Da. fill (DT) End using catch ex as exception me. lblmsg. TEXT = ex. message end try return DT end function private function deletedata (byval regionid as integer) as string dim RC as string = "" try using conn as new sqlconnection (connstr) Conn. open () dim sqltxt as string = "" sqltxt + = "delete region" sqltxt + = "where regionid = @ regionid" sqltxt + = "" using cmd as new sqlcommand (sqltxt, conn) cmmd. parameters. addwithvalue ("@ regionid", regionid) cmd. executenonquery () End using RC = "success" End using catch ex as exception rc = "false" me. lblmsg. TEXT = ex. message end try return RC end function private function upddata (byval regionid as integer, byval regiondescription as string) as string dim RC as string = "" try using conn as new sqlconnection (connstr) conn. open () dim sqltxt as string = "" sqltxt + = "Update region" sqltxt + = "set regiondescription = @ regiondescription" sqltxt + = "where regionid = @ regionid" sqltxt + = "" using cmmd as new sqlcommand (sqltxt, conn) cmmd. parameters. addwithvalue ("@ regiondescription", regiondescription) cmd. parameters. addwithvalue ("@ regionid", regionid) cmd. executenonquery () rc = "success" End using end using catch ex as exception rc = "false" me. lblmsg. TEXT = ex. message end try return RC end Function

Next, let's take a look at the various program categories including checking, checking, modifying, division, splitting, and sorting:

Query condition: when the data is pressed down, the data is routed to the gridview. Therefore, a sub gvgetdata () that links the data is processed first, in the future, there will be many places that need to call this sub for processing the final information.

 
'Capture the data and link it to the gridview private sub gvgetdata () Try Dim dT as datatable = getdata () me. gridview1.datasource = DT me. gridview1.databind () catch ex as exception me. lblmsg. TEXT = ex. message end try end sub

Next, when you press "continue", you only need to call him.

 
Protected sub button#click (byval sender as object, byval e as system. eventargs) handles button1.click' call the item response end gvgetdata () end sub

Next, let's take a look at how to do the shard. Set allowpaging = true for the gridview in minutes. In addition, there are not many resources for this data table, so modify it, the parameter number of a region is set to 10 bytes, and is changed to 3 bytes (pagesize = "3 "). At this time, there will be a split function, but when there is a split, there will be two events, pageindexchanging and pageindexchanged. Program example:

Protected sub gridview1_pageindexchanged (byval sender as object, byval e as system. eventargs) handles gridview1.pageindexchanged 'indicates that the pageindexchanged event is called to response. Write ("pageindexchanged !! ") End sub protected sub gridview1_pageindexchanging (byval sender as object, byval e as system. web. UI. webcontrols. gridviewpageeventargs) handles gridview1.pageindexchanging 'sets the minute to be stopped at the second hour when me. gridview1.pageindex = E. newpageindex 'additional response gvgetdata () end sub

Sorting: Check the shard and shard shards, and then sort the shards. During sorting, sorting and sorted events are reported. However, this part is a little troublesome. After the operation, it is found that in sorting's E. sortdirection does not remember this sort order (ascending) → next time, it will reverse the sort order (descending. all sortdirection statements use ascending ). In order to sort the cursor to the first vertex and then reverse the cursor, we need to go through the viewstate to record the previous method and add the comment.

In addition, there is no sorting for the original metadata. Only the retrieved datatable is directly sent to the gridview. Now we need to add the sorting function, so we need to use the data of the able for sorting. This part should be set by using the [sort] of [dataview, dataview can also be used as the data source of the gridview. Therefore, we need to modify the information first, and then sort the sorting and sorted events.

Link information:

There are too many types, so when sorting is expected, another type of response that calls gvgetdata must be called.

 
'Get the information in the specified sorting and link the gridview private sub gvgetdata (byval psortdirection as sortdirection, byval psortexpression as string) Try Dim dT as datatable = getdata () 'specify the sequence method dim strsort as string = "" If psortdirection = sortdirection. ascending then' if it is a Sort row (~ Z) strsort = psortexpression else 'reverse time (Z ~ A), add DESC strsort = psortexpression & "DESC" end if 'to use dataview for the gridview data to source dim DV as dataview = DT. defaultview 'sets the dataview sorting method DV. sort = strsort me. gridview1.datasource = DV me. gridview1.databind () catch ex as exception me. lblmsg. TEXT = ex. message end try end sub

Next, the sorting and sorted sections

Protected sub gridviewinclusorted (byval sender as object, byval e as system. eventargs) handles gridview1.sorted 'indicate that the sorted event triggers response. Write ("Sorted !! ") End sub protected sub gridview1_sorting (byval sender as object, byval e as system. web. UI. webcontrols. gridviewsorteventargs) handles gridview1.sorting dim nowse as string = ctype (viewstate ("nowse"), string) 'Current sorting direction dim nowsd as sortdirection = ctype (viewstate ("nowsd"), sortdirection) 'If nowse is nothing then' if no viewstate exists, specify E. sortexpression and cursor rank the positions and directions of the parameter set nowse = E. sortexpression nowsd = sortdirection. ascending else 'If nowse <> E. sortexpression then 'if the bitwise is different from the original ', specify the current bitwise as E. sortexpression nowse = E. sortexpression 'specifies that the current sorting direction is worker row nowsd = sortdirection. ascending else 'If the bitwise is the same as the original if nowsd = sortdirection. ascending then' is the reverse direction → changed to nowsd = sortdirection. descending else 'is the reverse sort → changed to nowsd = sortdirection. ascending end if 'will get the response bit and direction, then the response will return to viewstate ("nowsd") = nowsd viewstate ("nowse ") = nowse 'Call the response information and specify the sequence bit and the direction gvgetdata (nowsd, nowse) end sub

In this case, the sorting is OK. However, Xiao Miao found that this sub-sorting matches the sharding sequence, because the original sub-sorting does not take the test order, so every time the sub-sorting is complete, it will get sorted sort records. Therefore, you need to modify the Information Section and check whether the viewstate has a set sequence position and direction. Modify the original gvgetdata ()

 
'Capture the data and parse the gridview private sub gvgetdata () try' to determine whether the cursor has been sorted. If viewstate ("nowse") is nothing then' has not been sorted, directly capture datatable dim dT as datatable = getdata () me. gridview1.datasource = DT me. gridview1.databind () else 'has been sorted. Therefore, in addition to capturing data, you must also sort dim nowse as string = ctype (viewstate ("nowse"), string) dim nowsd as sortdirection = ctype (viewstate ("nowsd"), sortdirection) gvgetdata (nowsd, nowse) end if catch ex as exception me. lblmsg. TEXT = ex. message end try end sub

In this case, the sorting and sharding parts can all work normally.

Next, it is the Program program for deleting, modifying, and deleting. This small part of meow shows that when modification and division are performed in the delayed period, rowupdating and rowupdated/or rowdeleting and rowdeleted will be generated. However, in the actual step by step operation, it is suggested that the rowupdated event after updating and the modified rowdeleted event will not be released. This is different from the previous impression of meow. ing: Processing/ED: the understanding and expectation behind processing are different. Tom posted a comment in the small shop [Why does the manual Program handle the rowupdated event in the gridview ], it seems that the gridview does not use the performanceid to configure the datasource to control the metrics. The two ed events cannot be generated.

The following code lists the program types used for renewal, modification, cancellation, and Division:

Except data:

Protected sub gridview1_rowdeleted (byval sender as object, byval e as system. web. UI. webcontrols. gridviewdeletedeventargs) handles gridview1.rowdeleted 'displays rowdeleted when the program is released. In fact, the program cannot send this event !! Response. write ("rowdeleted") 'gvgetdata () end sub protected sub gridview1_rowdeleting (byval sender as object, byval e as system. web. UI. webcontrols. gridviewdeleteeventargs) handles gridview1.rowdeleting Try Dim regionid as integer 'partition key value' to obtain the key regionid = ctype (Me. gridview1.rows (E. rowindex ). cells (1 ). text, integer) 'Call the function dim RC as string = deletedata (regionid) If rc = "success" then me . Lblmsg. Text = "Division successful !! "'Call the Response Message to reinitialize gvgetdata () end if catch ex as exception me. lblmsg. Text = ex. Message end try end sub

Zookeeper:

Protected sub gridview1_rowediting (byval sender as object, byval e as system. web. UI. webcontrols. gridviewediteventargs) handles gridview1.rowediting 'sets the index me of the specified parameter. gridview1.editindex = E. neweditindex 'additional response gvgetdata () end sub

Cancel:

 
Protected sub gridview1_rowcancelingedit (byval sender as object, byval e as system. web. UI. webcontrols. gridviewcancelediteventargs) handles gridview1.rowcancelingedit 'cancel upload history mode → set editindex =-1 me of the gridview. gridview1.editindex =-1 gvgetdata () end sub

Modify:

Protected sub gridview1_rowupdated (byval sender as object, byval e as system. web. UI. webcontrols. gridviewupdatedeventargs) handles gridview1.rowupdated 'enabled when mode' me. gridview1.editindex =-1 'gvgetdata () response. write ("rowupdated") end sub protected sub gridview1_rowupdating (byval sender as object, byval e as system. web. UI. webcontrols. gridviewupdateeventargs) handles gridview1.rowupdating Try Dim regionid as integer dim regiondescription as string 'to obtain the information dim tgvrw as gridviewrow = me. gridview1.rows (E. rowindex) regionid = ctype (tgvrw. cells (1 ). controls (0), textbox ). text, integer) regiondescription = ctype (tgvrw. cells (2 ). controls (0), textbox ). text 'into plain dim RC as string = upddata (regionid, regiondescription) If rc = "success" then me. lblmsg. TEXT = "successfully completed" 'enable the zookeeper mode me. gridview1.editindex =-1 gvgetdata () end if catch ex as exception me. lblmsg. TEXT = ex. message end try end sub

Postscript

After such operations, some operations on the gridview will be clearer. It is said that such capabilities were the basic capabilities of the DataGrid in the past, that is, everyone must do so. Since ASP. NET 2.0, using gridview with datasource to control Metrics is really easy to use. To use sqldatasource, you only need to drag and set the parameters. In the next step, you need to understand the program, or you can compile it into a class that passes through objectdatasource. However, the requirement of the system is becoming more and more complex, and sometimes it is necessary to handle some transaction operations through the various browser events in the gridview. Through this sort of events, you can understand the usage of each event. Therefore, John will write down his documents and provide you with the exam.

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.