An Extensive Examination of the DataGrid Web Control: Part 6
By Scott Mitchell
The Sixth Part in a Multi-Part Series
This article is the sixth piece of a multi-part series on using the DataGrid Web control that will span
several months. The ASP.NET DataGrid Web control, which displays database information in an HTML table, is
highly versatile. The basics of the DataGrid were discussed in Part 1;
information on specifying display properties of the DataGrid was discussed in
Part 2. In Part 3
we examined how to associate custom events with the DataGrid.
In Part 4 we looked at how to extend
Part 3 to provide custom sorting on the results of a DataGrid. In
Part 5 we examined how to use templates to further customize
the DataGrid's appearance. In this part we look at how to
allow users to edit the data within a DataGrid!
ASP.NET Data Web Controls Kick Start is author Scott
Mitchell's most recent book, which thoroughly examines three of the most commonly
used ASP.NET Web controls: the DataGrid, DataList, and Repeater. These three Web controls
can be difficult to master due to their numerous features and capabilities. With this book, you'll
quickly become an expert, learning the gritty details and true capabilities of each.
This 400+ page book explores the topics in this article series in much greater depth, along with
examining various topics and techniques not covered here.
Scott Mitchell is the editor and founder of 4GuysFromRolla.com, author of the An Extensive Examination
of the DataGrid Web Control article series, and author of numerous other ASP and ASP.NET
books.
Introduction
Hopefully the past five installments of this multipart article series has, if nothing else, convinced
you that the DataGrid is a very useful Web control. In past articles we've seen how to
sort the results of a DataGrid and how to apply custom formatting
to the outputted HTML. You can even easily display XML data through
a DataGrid. In this article we'll examine yet another useful feature of the DataGrid - inline editing.
There are many situations where you'd like to be able to edit the data in a DataGrid. For example,
on a data-driven site you may have a set of administrative Web pages that list the full cotents
of the various database tables and allow the admin to alter the values in these database tables.
Using DataGrids we can very easily display a database table's information in a graphically pleasing
way (see Part 2 and Part 5
for more details); using the same control, though, we can also add support for editing the data within
the DataGrid!
Using the DataGrid's editing features is much more simple and requires far less code providing
the same functionality in a classic ASP page. Regardless, before tackling this article it is important
that you have an understanding of SQL, namely how to construct and UPDATE statement (for a refresher on
SQL be sure to consult the official SQL Books
Online). Also, it is imperative that you are confortable with the DataGrid and understand how
events are handled in the DataGrid. To brush up on this topic be sure to consult
Part 3 of this article series.
First Things First: Displaying the Data
Before we can even concern ourselves with editing the DataGrid's data, we must first be able to display
it in a DataGrid. I won't delve into lengthy explanations on this, since the means for displaying data
in a DataGrid has been heavily discussed in prior parts of this article series. Note that for this
example I will be using the GrocerToGo database (an Access 2000 database avaialbe in a download at the end of the article),
specifically displaying (and allowing the user to edit) the data in the Products database.
From the Products table the DataGrid will display the following columns: ProductID,
UnitPrice, ProductName, and ProductDescription. Some UI-formatting
code is also employed to make the DataGrid "look nice." The following code displays the
Products table in the DataGrid:
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack
BindData()
End If
End Sub
Sub BindData()
'1. Create a connection
Const strConnStr as String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\GrocerToGo.mdb"
Dim objConn as New OleDbConnection(strConnStr)
objConn.Open()
'2. Create a command object for the query
Const strSQL as String = "SELECT * FROM Products"
Dim objCmd as New OleDbCommand(strSQL, objConn)
'3. Create/Populate the DataReader
Dim objDR as OleDbDataReader
objDR = objCmd.ExecuteReader()
dgProducts.DataSource = objDR
dgProducts.DataBind()
End Sub
</script>
<asp:DataGrid id="dgProducts" runat="server"
AutoGenerateColumns="False" CellPadding="4"
HeaderStyle-BackColor="Black"
HeaderStyle-ForeColor="White"
HeaderStyle-HorizontalAlign="Center"
HeaderStyle-Font-Bold="True">
<Columns>
<asp:BoundColumn HeaderText="Product ID" DataField="ProductID" />
<asp:BoundColumn HeaderText="Price" DataField="UnitPrice"
ItemStyle-HorizontalAlign="Right"
DataFormatString="{0:$#,###.##}" />
<asp:BoundColumn HeaderText="Name" DataField="ProductName" />
<asp:BoundColumn HeaderText="Description"
DataField="ProductDescription" />
</Columns>
</asp:DataGrid>
This code is fairly straightforward and very similar to the code in live demos in previous installments
of this article series. The BindData() function simply reads in the contents of the
Products table into a DataReader and then binds that DataReader to the dgProducts
DataGrid.
Notice the Page_Load Event Handler!
Notice that the Page_Load event handler for the editable DataGrid only calls the
BindData() subroutine when the page is first visited. That is, it is not
called on subsequent postbacks. This is vital! If you change the Page_Load
event handler so that it calls BindData() every time, your edited values will not
be saved in the database. For a thorough explanation as to why this is the case, be sure to read
the FAQ: Why Your DataGrid's Updates Don't Show Up.
Now that we have the data displayed in our DataGrid we need to allow the user to edit the data. To
allow for this the DataGrid provides a control called EditCommandColumn, which displays
an "Edit" button next to each row in the DataGrid. We'll examine how this EditCommandColumn
control enables us to allow the end user to edit a particular row in the DataGrid in
Part 2 of this article.