Click here to Skip to main content
Email Password   helpLost your password?

Introduction

DataGrid is not a simple control to just present data but we can use this control in commercial applications using its different built-in properties. DataGrid control supports the display of repeating data such as database reports and queries. The DataGrid control renders to a table and includes a number of features that let you customize the appearance and enrich the overall functionality of the control.

Background

This sample I used the templated columns editing property of the DataGrid and modified the DataGrid in such a way that we can easily enter data into the controls inside the DataGrid and retrieve values from it so that the DataGrid will looks like a data entry form for the same type of data.

Sample Image - EditDataGrid.jpg

Screen shot of sample application looks like this.

The sample uses SQL Server 2000 database and the connection string is put in the Web.Config file. The advantage is even if the database connection string in the .config file changes, the application can be executed without recompiling it. The database design is also described below. The sample code downloads are also available in C# and Visual Basic .NET.

DataGrid Editing

DataGrid provides EditCommandColumn control for editing. The EditCommandColumn control adds a new column to the DataGrid, placing an edit button next to each row. The button, when clicked, causes a postback and the EditCommand event is fired. We have to write code for handling this event.

<Columns>
    <asp:EditCommandColumn EditText="Edit"  ID="DataGrid1"  
          ButtonType="PushButton"
          UpdateText="Update" CancelText="Cancel" />
</Columns>

The EditCommandColumn control's ButtonType includes the default LinkButton and PushButton. The EditItemIndex property of DataGrid specifies what row of the DataGrid is being edited. DataGrid is not able to edit the data by itself, so when the edit button is clicked, we have to write code to EditCommand event handler. The EditCommand event handler is the DataGrid event handler that is fired when the Edit button is clicked. This event handler simply needs to set the EditItemIndex property to the row whose Edit button was clicked and then rebind the DataGrid. The numbering of DataGrid rows starts at 0, and by default, EditItemIndex has a value of -1.

DataGrid1.EditItemIndex = e.Item.ItemIndex;

The Cancel button is to return the DataGrid to its non-editing state without saving any changes. The Cancel button also fires the CancelCommand event. In the code behind, we have to set the EditItemIndex property to -1 and rebind the DataGrid control.

The Update button fires an event UpdateCommand when it is clicked. The DataGrid doesn't provide any facility for updating, and we are responsible for updating. The Update button's event handler accepts two incoming parameters, an Object and a DataGridCommandEventArgs. The DataGridCommandEventArgs parameter contains a PropertyItem, which is an instance of the DataGridItem that corresponds to the DataGrid row whose Update button was clicked. This DataGridItem object contains a Cells collection, which can be iterated to retrieve the text or controls at the various columns of the DataGrid. To determine the user entry values, we have to use the DataGridItemobject.

Database

Consider the employee table of a software firm that stores all the employee records. The table can be created using the following CREATE TABLE statement:

CREATE TABLE [dbo].[EMPLOYEEDETAILS] (
 [ID] [int] IDENTITY (1, 1) NOT NULL ,
 [NAME] [char] (20) NULL ,
 [DESIGNATION] [char] (20) NULL ,
 [SEX] [char] (20) NULL ,
 [AGE] [int] NULL ,
 [SALARY] [decimal](18, 0) NULL 
) ON [PRIMARY]
GO

You can create the above said table either in a new database or in any existing database. The DataGrid in the sample application is going to bind with the above said table.

How the code works?

To convert the DataGrid into a data entry form, define an edit template and populate the column cell with as many HTML controls and as much code as needed for effective data entry. In the sample application, instead of Edit, Cancel and Update buttons, I used different images.

<asp:TemplateColumn HeaderText="AGE">
 <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
 <ItemTemplate>
  <asp:label runat="server" 
      Text='<%# DataBinder.Eval(Container.DataItem, "AGE")  %>' 
      ID="Label3" />
 </ItemTemplate>
 <EditItemTemplate>
  <asp:textbox runat="server" 
      Text='<%# DataBinder.Eval(Container.DataItem, "AGE") %>' 
      ID="Textbox2" />
 </EditItemTemplate>
</asp:TemplateColumn>

The ItemTemplate is the keyword which identifies the HTML template to be used for normal rendering. AlternatingItemTemplate is the template name for rows rendered on even positions. For rows under editing, the template name is EditTemplateName. A Templated column must have a chance to define how its cells have to be rendered under all possible circumstances. This includes the normal and the alternating item and the item's appearance when the row is selected or edited.

ASP.NET data-binding techniques let you associate an inline control such as a Label or TextBox with text coming from a data source. Since we have to retrieve the current values from the controls in the EditItemTemplate, we have to assign unique ID to the controls. Data binding results in fewer trips to the server, since you normally won't need to interact with the server once the requested data has been downloaded. A data source can be any object that implements System.Collection.ICollection interface.

DataBinder.Eval(Container.DataItem, fieldname);
DataSource='<%# ListOfDesignations()%>

The DataBinder class provides a static method Eval that uses reflection to parse and evaluate a data binding expression against an object at run time. The ASP.NET <%# syntax binds the value returned by the Eval to a Control or DataGrid cells. The local function ListOfDesignations must return a type derived from ICollection because that is what the DataSource property expects to receive.

The Cancel button and Edit button works in the same manner as that of normal DataGrid explained early, but to update the content of an editable DataGrid, we have to retrieve the fresh information from the controls involved in the update. We can write code in the Datagrid1_Update to retrieve the values from the control using any of the following methods:

TextBox tb =  (TextBox) e.Item.FindControl("Textbox2");

Or

TextBox tb =  (TextBox) e.Item.Cells(2).Controls(0);

We can refer each control using the zero-based ordinal position of the column. Since we are using templates for editing, the controls are generated by us and we know the necessary IDs. FindControl is a method of the Control class that searches for a child control with the specified name.

In this sample, Edit button is used for handling both new entry and editing using the ID field of the database. If the ID is null, then we can conclude that the user is going to enter a new data and the ID field is set to read only in DataGrid so that the user is not able to edit the ID.

Conclusion

DataGrid control has uses beyond presentation of data, it can also be used to allow editing with simple line codes. I hope this article helps to understand more about DataGrid editing.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
QuestionHi, I'm getting an error trying to compile and can't figure it out...
howardbg
8:54 20 Nov '09  
Error 9 Could not load type 'CSharpDemoEditGrid.WebForm1'. C:\workspaces\Dev\source\EverBank\Servicing\Sandbox\EditDatGrid_CS_src\CSharpDemoEditGrid\DemoForm.aspx 1


Any ideas?
Thank you.
GeneralCan a Data Grid be used for simple data entry
Member 1718072
11:04 9 Oct '09  
I would like to use the data grid to create a grid for data entry. As an example, suppose I wanted to enter order information:

Quantity Code # Description Unit Price Extended Price

5 101 Widgets $10.00 $50.00
10 102 Wombats $20.00 $200.00


Can data grid be used to do this?

Is it required to bind the data grid to a database or can I just put up a data grid and be able to collect this data and then do what I want to do with it?
GeneralEquivalant code in for Win forms
infotools
21:05 24 Nov '07  
Hello,

do you have eqivalant code in VB.Net? am not good at handling C# code.

Also wish to implement in Windows forms.



thanks,


Madhav

Generalopening the application
sudhasurana
9:15 30 May '06  
I am not able to view and run the application on click .sln file It will me an error that it is not a valid solution file. How do I view and run this project.......

thanx

GeneralRe: opening the application
Jimmy M Joy
16:33 30 May '06  
Please check your VS.NET version.
Generalneed some help here.. (rather urgent)
chubbie
17:36 18 Jan '06  
hi Jimmy,

i have downloaded your sample source code (C#)..
i am currently using ASP .NET 2.0..

i've opened the file [CSharpEditGrid/DemoForm.aspx] and viewed the source code..
but i need the code-behind for reference..
mind giving me some tips so i can have a headstart with my project..?
this article you've posted is exactly what is required in my project..
therefore, i am seeking your assistance..

thanks for the attention to this message..

-DarkangeL-
GeneralRe: need some help here.. (rather urgent)
Jimmy M Joy
19:47 27 Jan '06  
I'm not clear what you mean by source code and code-behind. if you are trying to implement this in ur project first copy the presentation part from the aspx file and copy the code from the .cs file.

Regards,
Jim
GeneralDebug failure?
fire85
1:12 30 May '05  
Sorry i just started Visual Studio.net so please help me if you have time Smile

Error of mine:
----------------------------------------------------------
Error while trying to run project: Unable to start debugging on the web server. The project is not configured to be debugged.
----------------------------------------------------------

THanks Smile
GeneralRe: Debug failure?
Jimmy M Joy
0:14 13 Jun '05  
I hope that this is coz of ur IIS Configuration problem. you have to go to the IIS Manager and right click on the project folder then you have create the application name by clicking the Create button which is close to the text box.
GeneralRe: Debug failure?
fire85
18:21 14 Jun '05  
Yup Smile Thanks alot Jimmy Smile

fire85.
GeneralValue set EditItemTemplate on EditCommand
Ilman
6:24 3 Feb '05  
i have two ddl's and a calendar in EditItemTemplate. Is there a way to set their values on EditCommand? Its really easy to pull the info out but no way to set because when i cast the control its disconnected. hmmm. that made me think...maybe I can cast it ByRef
GeneralRe: Value set EditItemTemplate on EditCommand
Ilman
7:35 3 Feb '05  
well, i lied, i have not found a way to populate anything else but the default value in a cell, (Container.DataItem) if you have something else in the same cell, forget it.
GeneralHas anyone gotten this to work?
asoong
14:17 30 Dec '04  
I'm a .Net newbie so bear with me if this is a stupid question...   I'm trying to use the C# version of the source code and I get the following error:

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type 'CSharpDemoEditGrid.Global'.

Source Error:


Line 1:   <%@ Application Codebehind="Global.asax.cs" Inherits="CSharpDemoEditGrid.Global" %>



Source File: c:\inetpub\wwwroot\CSharpDemoEditGrid\global.asax      Line: 1


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573
GeneralRe: Has anyone gotten this to work?
asoong
11:52 4 Jan '05  
Nevermind... I was being stupid again...


Last Updated 16 Sep 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010