Thursday, January 11, 2007

DataGrid Control in ASP.NET by VS.NET

Summary

We need fast coding, especially when there lots of data needed to be accessed through the web. We need an efficient way to create interfaces for the users to manipulate the data. DataGrid is one of the very useful controls in ASP.NET, and VS.NET even maximize its efficiency by keeping the code that we need to write to a minimum.

.NET Classes used :

Introduction

We need fast coding, especially when there lots of data needed to be accessed through the web. We need an efficient way to create interfaces for the users to manipulate the data. DataGrid is one of the very useful controls in ASP.NET, and VS.NET even maximize its efficiency by keeping the code that we need to write to a minimum.

Connect to a database

ADO.NET to do this. In this walkthrough, we will connect to an Access Northwind database, so please get ready with your .mdb file. We have to make a connection to Northwind, define the what data we want to get, fill the data into a DataSet and then hold the data in a DataView, and finally bind a DataGrid to the DataView for display.

Create a new project

First of all, we have to create an ASP.NET web application, let's name it Prod. remember to choose C#.

Connecting to the Database

You will see WebForm1. In Server Explorer (under the View menu), right click on Data Connections and choose Add Connection.

The Data Link Properties dialog box appears. On the Provider tab, choose Microsoft Jet 4.0 OLE DB Provider, for we are connecting to an Access Database, not a SQL Server. On the Connection tab, choose the path of your Northwind Database. Click Test Connection to make sure the connection is working. Click OK.

Configuring DataAdapter

Next, go to ToolBox and choose the Data tab. You will see OleDbDataAdapter. Click on it and drag one onto WebForm1.

The Data Adapter Configuration Wizard appears. Click Next. Then you should see the connection to Northwind Database already chosen for you. Click Next. Choose Use SQL statements and click Next. In this window you have to define your SQL statement. Type the following SQL statement in the box or build it using the Query Builder.

SELECT ProductID, ProductName, UnitsInStock, UnitsOnOrder FROM Products
Click the Advanced Option button and choose only Generate Insert, Update and Delete Statement, choosing the other options generates extra codes that is not suitable for this demo. Press Next and you should see five ticks. Click Finish and go back to design view.

You can see two icons at the bottom of the design area. Choose the connection icon and press F4 to bring up the properties window, let's name the connection Conn and the DataAdapter cmdProd.

Right click on WebForm1 and choose View Code. In WebForm1.aspx.cs, scroll down to find Web Form Designer generated code in gray. Expand it to see what VS.NET has done for you.

Generating DataSet

Now we are ready to generate the DataSet, but before that, we can preview the data by right click on cmdProd and choose Preview Data. Click the Fill Dataset button to preview.

Right click on cmdProd and choose Generate DataSet. Name the DataSet dsProd and click OK. You'll see dsProd1 added to the designer. dsProd1 is an instance of dsProd. Notice that dsProd.xsd is added in the Solution Explorer, double click it to examine the schema.

Creating DataView

From the Data tab in ToolBox, drag a DataView and drop it to WebForm1. Rename the DataView to dvProd. In its Table Properties, expand dsProd1 and choose Products.

Binding DataView to DataGrid

Bare in mind we have not written a single line of code yet, we are going to bind dvProd to a datagrid for display. Drag a DataGrid to WebForm1. It is named DataGrid1 and let's leave it as it is. In its DataSource property, choose dvProd. Notice the visual change of DataGrid1.

Setting the DataSource property alone will not bind dvProd to DataGrid1. We have to add some code to do the binding. We have to fill the DataSet and bind the DataGrid at runtime. Since these two steps usually comes together, putting them in a BindGrid() method is a good idea. Add the following code in WebForm1.aspx.cs as shown.

public void BindGrid()
{
cmdProd.Fill(dsProd1, "Products");
DataGrid1.DataBind();
}


Add these two lines of code in Page_Load()

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack)
BindGrid();
}




By now you should be able to see the results. Right click on WebForm1.aspx in solution explorer and choose Build and Browse.

Make it looks better
Right click on DataGrid1, choose AutoFormat, and pick your favourite style.

Add Paging
Right click on DataGrid1, choose Property Builder. In the General tab, set the Data key field to ProductID. The Data key field is usually the primary key of the data source.

In the Paging tab, check Allow paging and set the navigation buttons to your favourite settings. Click OK.



Bring up the Property window for DataGrid1, on the top you can find an Events button. Click on it and find the SelectedIndexChanged event. Double click on that word and the DataGrid1_PageIndexChanged() method will be added to WebForm1.aspx.cs. Put these two lines of code in it to catch the new page index and rebind the datagrid every time the page index is changed.

private void DataGrid1_PageIndexChanged
(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex=e.NewPageIndex;
BindGrid();
}


Build and browse to see how it works.

Add Sorting ability to the DataGrid
Right click on DataGrid1 and choose Property Builder. At the bottom of the General tab, choose Allow sorting and click OK. In the Property Window of DataGrid1, choose the lightning button to display the events. Double click on SortCommand, the DataGrid1_SortCommand() method will be added.

private void DataGrid1_SortCommand
(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
dvProd.Sort = e.SortExpression.ToString();
BindGrid();
}