It would be hard to find a web developer who doesn’t need to use a DataGrid. This control is ideal for data presentation. Besides the visualization, it provides a powerful set of possibilities to edit, delete, add and update data.
ASP.NET includes a well designed, powerful DataGrid Web Server Control which makes the life of web developers easier. I remember the time when we had to implement the grid's functionallity manually in classic ASP. And, although, a lot of time has passed since first ASP.NET was released and a lot of information exists on the web, still there are a quite a bit of questions asked on forums about DataGrid features.
In this article I will demonstrate some DataGrid features such as editing, updating, deleting, sorting, paging, etc. which are quite often used by many web developers.
Binding to data source
As usual, working with DataGrid begins with a data source. As data source, I used the well known Nwind database. Our DataGrid is bound on ‘Products’ table. Why Products table? Because it contains relationships with other tables such as ‘Categiries’, ‘OrderDetails’ and ‘Suppliers’.
Here is a screenshot of the tables relationship:
It models a situation when thedeveloper needs to display some related tables in DataGrid.
For binding, every table in the database should be converted to a DataTable object. How to do it? We need to create a new DataSet item, drag an object from Server Explorer. Visual Studio generates a DataSet class which contains a DataTable you entered.
Is that all? No. As we are going to do some operations on every table, it will be nice to create a small business layer. So, for every table, I created a component class which encapsulates logic for select, delete update a data from particular table.
Let’s take a look at the HTML code in the ASPX page that creates the DataGrid:
<asp:datagrid id=ProductsDataGrid runat="server"
DataSource="<%# Products %>"
<ItemStyle Wrap="True" BorderStyle="None" CssClass="BodyText"></ItemStyle>
<HeaderStyle HorizontalAlign="Center" CssClass="ListHeader"></HeaderStyle>
As we see, DataGrid has powerful built-in features for customizing layout . You can play with such features by changing ItemStyle, HeaderStyle, color schema etc. After loading a page, the user is presented a DataGrid like this: