Multi-row editing in the ASP. NET DataGrid...
This articles demonstrates how you can have multiple DataGrid rows available for editing at one time, not just the one row you are normally limited.
By: Shajahan kakkattil ("shaji") Date: August 28,200 3 download the code. Printer friendly version
Introduction
The ASP. net DataGrid is a vital part. net web programming and is the highly discussed Control Among news groups and discussion forums. no wonder Microsoft has a newsgroup (DOTNET. framework. ASPnet. datgridcontrol) solely pinned Ted for the DataGrid!
You can use the DataGrid to display as well as to edit data. the default in-place editing is a cool feature of the DataGrid but it is restricted to edit and update one row at a time by enabling the "edititemindex" property and by handling editcommand, updatecommand and cancelcommand to intiate edit, update and cancel editing respectively. obviusly there are limitations to enable Windows form or Excel Style editing as far as the Web application development is concerned.
However, in real life scenarios we may face situations where we really need to enable multi row editing, but without losing the easiness of coding with Asp.net server controls.
This tutorial discusses a technique to enable the DataGrid for multi row editing.
Scenario
Suppose that we have a web form which allows candidates to update their resume details, something like a wizard which collects the relevant information in each step. one of the intermediate steps is say, entering the work experience details of the candidate. this is a set of line entries in which the candidate can enter any number of rows which he needs, and can come back and edit it on the fly.
We are using a data grid to do this with multi row editing facility.
The Technique
Before jumping to the implementation details of this scenario, let me put up how we are achieving this for those who are so curious. as mentioned earlier, we cannot use the default "edititemindex" property here because it can be set only to a single row. if it set to multiple rows the last row will override the others and only the last row will be in edit mode.
Here, we use "template columns" for all the Editable columns as in the normal inplace editing. but the difference is we don't use the "edititemtemplate", instead the "itemtemplate" itself is used for item editing. appropriate edit controls (Textbox, combo box, check box, etc .) will be placed in the "itemtemplate" of the template column. then bind the DataGrid with the datasource and display the data in the template columns. so, upon displaying the grid in the browser all rows will be rendered with editing controls and the data can be entered/edited and posted back to the server.
Things are straight forward up to this point, but how do we get back the edited data and merge with the data set? That is DataGrid. databind set the data to the DataGrid, but we need to get back the data from the grid to the dataset after the user edited the data. yes we need the reverse process of the DataGrid. databind ...... Maybe DataGrid. reversebind! But unfortunately DataGrid does not support anything as such.
If there is nothing built-in, then we build up! But it is easy, loop thru each rows and collect the data back. Here is the code snippet that implements "reversebind" for the application which we are going to build.
Public sub reversebind () 'This function is the heart of this application. 'It reads each grid rows, get the edited data And serialize back to the dataset. 'Yes the reverse process of "DataGrid. databind", hence the name.'The grid row Dim gridrow as datagriditem 'Typed data set row Dim datarow as dataset1.workexperiancedatarow 'Loop thru each grid row and synchronize the edited data 'With the corresponding data set. 'In this demo the typed data set has a one to one mapping 'With the templated columns for the sake of simplicity. For each gridrow in datagrid1.items '"Datsetindex" property of the gridrow gives 'References' to the datrow used for binding Datarow = _ dataset. workexperiancedata (gridrow. datasetindex) 'Get the data from grid Row Element and update the column in the 'data row Datarow. experianceperiod = ctype (gridrow. findcontrol ("experianceperiod"), textbox). Text '(Note: The hardcoded control names is not a good programming' practice, better to use 'A constant instead .) 'Reverse bind the other fields Datarow. totalyears = cshort (ctype (gridrow. findcontrol ("totalyears"), textbox). Text) Datarow. companyName = ctype (gridrow. findcontrol ("companyName"), textbox). Text Datarow. jobdescription = ctype (gridrow. findcontrol ("jobdescription"), textbox). Text 'Update the data tabe with new values. _ Dataset. workexperiancedata (gridrow. datasetindex). itemarray = datarow. itemarray Next End sub |
Please note that the DataGrid in question is datagrid1 and the datasource is "dataset1.workexperiancedata" which is a typed dataset table with 4 columns (experianceperiod, totalyears, companyName, jobdescription ). also, the DataGrid has template columns to edit these fields respectively.
The key point here is getting the reference of the dataset row used for binding each row, then updating the datarow with the edited data. In the above mentioned code snippet it is done by the following code
Datarow = _ dataset. workexperiancedata (gridrow. datasetindex) |
Where, "_ dataset" is a form level variable which holds the typed dataset with work experience data.
Demo Application
Let us have a look at how this is implemented in this demo application. it demonstrates the multi row data entry for the "work experience" Data Entry scenario. when the form first loads the grid shows a set of rows in edit mode with some initialization data. the existing data can be edited and deleted; also new rows can be added. you can add multiple rows at a time by specifying the number of rows to add. also the paging is enabled, so during editing you can navigate thru the pages before making the final update by clicking the "Update" button.
Controls
Following are the main server controls used in the application ."Datagrid1"Is used for entering and editing the data. The definition of datagrid1 is as follows:
<Asp: DataGrid id = "datagrid1" runat = "server" autogeneratecolumns = "false" pagesize = "5" allowpaging = "true"> <Columns> <Asp: templatecolumn headertext = "Period"> <Itemtemplate> <Asp: textbox id = "experianceperiod" runat = "server"> </ASP: textbox> </Itemtemplate> </ASP: templatecolumn> <Asp: templatecolumn headertext = "No of years"> <Itemtemplate> <Asp: textbox id = "totalyears" runat = "server" width = "70px"> </ASP: textbox> <Asp: comparevalidator id = "comparevalidator1" runat = "server" type = "integer" Operator = "datatypecheck" controltovalidate = "totalyears" Errormessage = "No of years-numeric value expected">! </ASP: comparevalidator> </Itemtemplate> </ASP: templatecolumn> <Asp: templatecolumn headertext = "Name of the company"> <Itemtemplate> <Asp: textbox id = "companyName" runat = "server" width = "256px"> </ASP: textbox> </Itemtemplate> </ASP: templatecolumn> <Asp: templatecolumn headertext = "job description"> <Itemtemplate> <Asp: textbox id = "jobdescription" runat = "server" width = "224px"> </ASP: textbox> </Itemtemplate> </ASP: templatecolumn> <Asp: templatecolumn headertext = "delete"> <Itemtemplate> <Asp: linkbutton id = "deleterow" runat = "server"> x </ASP: linkbutton> </Itemtemplate> </ASP: templatecolumn> </Columns> <Pagerstyle nextpagetext = "Next" prevpagetext = "previous" Horizontalalign = "center" mode = "numericpages"> </Pagerstyle> </ASP: DataGrid> |
"Dataset1"Is a typed dataset having a table with 4 fields.
[Note: headers omitted for simplicity] <Xs: element name = "dataset1" msdata: isdataset = "true"> <Xs: complextype> <Xs: Choice maxoccurs = "unbounded"> <Xs: element name = "workexperiancedata"> <Xs: complextype> <Xs: sequence> <Xs: element name = "experianceperiod" type = "XS: string" minoccurs = "0"/> <Xs: element name = "totalyears" type = "XS: short" minoccurs = "0"/> <Xs: element name = "companyName" type = "XS: string" minoccurs = "0"/> <Xs: element name = "jobdescription" type = "XS: string" minoccurs = "0"/> </Xs: sequence> </Xs: complextype> </Xs: Element> </Xs: Choice> </Xs: complextype> </Xs: Element> |
Other controls
Addrows; Link button to add additional rows
Save; Command button. The data is not saved to anywhere instead it is displayed in "datagrid2" in read-only mode
Datagrid2; DataGrid to show the edited data.
The important methods and event handlers are explained below. For the full listing please refer to the source code of the application provided with this tutorial.
Page_load event
Initialize the data and bind the grid if the page is loading for the first time. we are using a stub method "initializedata" for loading the data with some values for the first time. on each post back the data is binding back to the data set from the grid by calling "reversebind ()".
Private sub page_load (byval ...........) Handles mybase. Load 'Put user code to initialize the page here If not ispostback then 'Load the data for the first time Initializedata () Bindgrid () Else 'Get the edited data, and populate back to the data holder '(Dataset) Reversebind () End if End sub |
Initializedata
Loading some start up data.
Private sub initializedata () 'Initializing the data for the first time.'This is just a "stub" to load some startup data for demo purpose only. 'Normally the data will be loaded from data provider (database) or it can be empty initially. With _ dataset. workexperiancedata . Addworkexperiancedatarow ("1/Jan/1988 to 31/DEC/2000", 3, "IBM", "bulding IBM mainframe systems ") Etc ...... Etc ...... End End sub |
Loadviewstate/saveviewstate
The edited data collected from the grid is stored in the dataset, And the dataset is persisted in a viewstate variable called "data ". again, you can implement your own logic to persist the data, but using the viewstate is ideal in most situations, provided that the dataset is not so huge. for the database programmers, if the underlying dataset is huge then it is better to use a custom dataset to collect required data from the user, then load it back to the dataset representing your database tables before making a database update.
To enable the viewstate variable as our temporary data store the "loadviewstate" and "saveviewstate" are overridden as follows.
Protected overrides sub loadviewstate (byval savedstate as object) Mybase. loadviewstate (savedstate)'Get the dataset from the viewstate. This is the data before last editing If (not me. viewstate ("data") is nothing) then _ Dataset = ctype (Me. viewstate ("data"), dataset1) End if If (not me. viewstate ("lasteditedpage") is nothing) then 'Just a variable to keep the last edited page index for the purpose of this application _ Lasteditedpage = ctype (Me. viewstate ("lasteditedpage"), integer) End if End sub Protected overrides function saveviewstate () as object 'The datset used for editing needs to be persisted into SS postbacks. 'The performance will be affected if the dataset is huge in size. Please 'Refer the tutorial for more details Me. viewstate ("data") = _ Dataset Me. viewstate ("lasteditedpage") = _ lasteditedpage Return (mybase. saveviewstate ()) End Function |
Addrow_click
Adding new rows to the application. This is the event handler of command button "addrow ".
Private sub addrow_click (byval sender as system. Object, byval e as system. eventargs) handles addrow. Click 'Add the number of rows specified by "rowcount" to Grid If (isnumeric (rowcount. Text) then Dim I as integer For I = 1 to CINT (rowcount. Text) 'Adding a blank record to the dataset. _ Dataset. workexperiancedata. addworkexperiancedatarow ("", 0 ,"","") 'In our case the typed datset has only a few fileds, so that it is 'Easy to pass the default data as arguments. If there are invalid 'Fields (that is the case usually in real life scenarios) 'Instatiate a data row and load initialization data one by one. Then 'Plug it into the data table. 'You can even pass blank row with out initialization data, but in 'That case you need to handle "dbnull" situation during grid row 'Binding either by checking "isdbnull" or 'Setting default value property for the field in the dataset. Next End if 'Rebind the grid to show the newly added row (s ). Bindgrid () End sub |
Datagrid1_itemdatabound
Nothing special, simply populating the templated controls with data during grid bind.
Private sub maid (byval sender as object, byval e as system. Web. UI. webcontrols. datagriditemeventargs) handles maid 'This event handler is executed once per each row of the DataGrid 'While binding the dataset records. 'The templated Controls get populated with data here from 'The "workexperiance" data table If (E. Item. itemtype = listitemtype. item or E. Item. itemtype = listitemtype. alternatingitem) then Dim datarow as dataset1.workexperiancedatarow Datarow = ctype (E. Item. dataitem, datarowview). Row, dataset1.workexperiancedatarow) Ctype (E. Item. findcontrol ("experianceperiod"), textbox). Text = datarow. experianceperiod Ctype (E. Item. findcontrol ("totalyears"), textbox). Text = datarow. totalyears. tostring Ctype (E. Item. findcontrol ("companyName"), textbox). Text = datarow. companyName Ctype (E. Item. findcontrol ("jobdescription"), textbox). Text = datarow. jobdescription End if End sub |
There are couple of other methods also to complete the functionality of the application but are not worth mentioning here. See the "webform1.aspx" for a complete code listing.
Conclusion
This is not a ready made solution suitable for all multi-row data editing requirements, but the technique can be adopted for processing situations. I think there are only minor changes required for Microsoft to enable multi-row editing in the grid control. for instance, by providing a property called "enableediting" at the row level, and if it is true that row shoshould be rendered using "itemedittemplate ". also the update and cancel edit commands shoshould be provided in the grid level, not in the row level. upon PostBack itemupdate event shoshould be raised for each row which had the "enableediting" set to true. the data can be read back from the grid at this point, the exact reverse process of itemdatabound event handler. let me see if I can mange to customize the grid to enable this, I will surely get back here if can.
You may run the program here.
You may download the code here.