Click here to Skip to main content
12,401,995 members (38,544 online)
Click here to Skip to main content
Add your own
alternative version

Stats

211.6K views
7.9K downloads
90 bookmarked
Posted

How to convert DataGrid into Data Entry Form

, 16 Sep 2004
Rate this:
Please Sign up or sign in to vote.
This article explains how to convert DataGrid into a data entry form for same kind of data.

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" />

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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Jimmy M Joy
Web Developer
United States United States
Jimmy M Joy - Microsoft Application Developer

You may also be interested in...

Comments and Discussions

 
Questiondatagridview Pin
Member 1018971918-Nov-14 2:49
memberMember 1018971918-Nov-14 2:49 
QuestionHi, I'm getting an error trying to compile and can't figure it out... Pin
howardbg20-Nov-09 7:54
memberhowardbg20-Nov-09 7:54 
QuestionCan a Data Grid be used for simple data entry Pin
Member 17180729-Oct-09 10:04
memberMember 17180729-Oct-09 10:04 
GeneralEquivalant code in for Win forms Pin
infotools24-Nov-07 20:05
memberinfotools24-Nov-07 20:05 
Generalopening the application Pin
sudhasurana30-May-06 8:15
membersudhasurana30-May-06 8:15 
GeneralRe: opening the application Pin
Jimmy M Joy30-May-06 15:33
memberJimmy M Joy30-May-06 15:33 
Generalneed some help here.. (rather urgent) Pin
chubbie18-Jan-06 16:36
memberchubbie18-Jan-06 16:36 
GeneralRe: need some help here.. (rather urgent) Pin
Jimmy M Joy27-Jan-06 18:47
memberJimmy M Joy27-Jan-06 18:47 
QuestionDebug failure? Pin
fire8530-May-05 0:12
memberfire8530-May-05 0:12 
AnswerRe: Debug failure? Pin
Jimmy M Joy12-Jun-05 23:14
memberJimmy M Joy12-Jun-05 23:14 
GeneralRe: Debug failure? Pin
fire8514-Jun-05 17:21
memberfire8514-Jun-05 17:21 
GeneralValue set EditItemTemplate on EditCommand Pin
Ilman3-Feb-05 5:24
memberIlman3-Feb-05 5:24 
GeneralRe: Value set EditItemTemplate on EditCommand Pin
Ilman3-Feb-05 6:35
memberIlman3-Feb-05 6:35 
QuestionHas anyone gotten this to work? Pin
asoong30-Dec-04 13:17
memberasoong30-Dec-04 13:17 
AnswerRe: Has anyone gotten this to work? Pin
asoong4-Jan-05 10:52
memberasoong4-Jan-05 10:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 16 Sep 2004
Article Copyright 2004 by Jimmy M Joy
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid