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.
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.