Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Build Your Own ASP.NET 2.0 Web Site Using CSharp And VB (2006) [eng].pdf
Скачиваний:
77
Добавлен:
16.08.2013
Размер:
15.69 Mб
Скачать

Chapter 12: Advanced Data Access

It’s easy to imagine how quickly you could fill a page containing many GridViews using only one DataSet as the source.

As you’ve learned thus far, DataTables are elements that hold data within a DataSet. Just like tables in a database, DataTables are built from columns and rows. However, unlike tables in databases, DataTables reside in memory, which gives us the ability to page, sort, and filter the data in ways that just wouldn’t be possible with an SqlDataReader.

Implementing Paging

We saw the GridView’s paging functionality in action earlier in this chapter. When we bound the GridView to the SqlDataProvider, the paging functionality was automatically implemented. Now that we’re binding the GridView to a DataSet, there’s a little more work involved in getting paging up and running. However, the effort will be more than worthwhile if performance is an issue in your application.

The task of implementing paging in a GridView that has been bound to an SqlDataAdapter is a two-step process. First, we need to set the AllowPaging property of the GridView to True, and set its PageSize value to reflect the number of items we want to see on every page. Open Departments.aspx in Visual Web Developer and set AllowPaging to True, and PageSize to 4 on the departmentsGrid control, as shown below:

File: Departments.aspx (excerpt)

<asp:GridView id="departmentsGrid" runat="server"

AllowPaging="True" PageSize="4"> </asp:GridView>

Next, we need to handle the PageIndexChanging event of the GridView control. This event is fired when the user clicks one of the paging controls; we’ll need to update the data displayed in the grid accordingly.

Double-click the PageIndexChanging entry in the Properties window, as shown in Figure 12.24, to have Visual Web Developer generate an empty PageIndexChanging event handler for you.

504

Implementing Paging

Figure 12.24. Creating the PageIndexChanging event handler

Finally, fill in the generated event handler as shown below:

Visual Basic

File: Departments.aspx.vb (excerpt)

 

 

Protected

Sub departmentsGrid_PageIndexChanging( _

ByVal

sender As Object, _

ByVal

e As System.Web.UI.WebControls.GridViewPageEventArgs) _

Handles departmentsGrid.PageIndexChanging ' Retrieve the new page index

Dim newPageIndex As Integer = e.NewPageIndex

'Set the new page index of the GridView departmentsGrid.PageIndex = newPageIndex

'Bind the grid to its data source again to update its contents BindGrid()

End Sub

C#

File: Departments.aspx.cs (excerpt)

protected void departmentsGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

// Retrieve the new page index

int newPageIndex = e.NewPageIndex;

//Set the new page index of the GridView departmentsGrid.PageIndex = newPageIndex;

//Bind the grid to its data source again to update its

//contents

BindGrid();

}

In this code, we’ve retrieved the index of the requested page from e.NewPageIndex parameter, and used its value to set the PageIndex property of the GridView. We’ve then bound the grid to its data source once more.

505

Chapter 12: Advanced Data Access

Execute the project again. When you click a paging link within the grid, the display should update quickly, as Figure 12.25 shows.

Figure 12.25. Viewing Departments with paging functionality

Storing Data Sets in View State

Now, we’re able to page through our list of departments, but the code isn’t anywhere near as efficient as it could be. Every time we display another page of departments in our GridView, we call the BindData method, which executes the following code in order to retrieve a list of departments:

Visual Basic File: Departments.aspx.vb (excerpt)

' Initialize connection

conn = New SqlConnection(connectionString) ' Create adapter

adapter = New SqlDataAdapter( _

"SELECT DepartmentID, Department FROM Departments", conn) ' Fill the DataSet

adapter.Fill(dataSet, "Departments")

506

Storing Data Sets in View State

C# File: Departments.aspx.cs (excerpt)

// Initialize connection

conn = new SqlConnection(connectionString); // Create adapter

adapter = new SqlDataAdapter(

"SELECT DepartmentID, Department FROM Departments", conn); // Fill the DataSet

adapter.Fill(dataSet, "Departments");

Given that this list of departments is unlikely to change a great deal, wouldn’t it be better if we had to query the database only once? Well, given that we now have a complete copy of the data in the Departments table, we can! Modify the BindGrid method as shown below:

Visual Basic File: Departments.aspx.vb (excerpt)

Private Sub BindGrid() ' Define data objects

Dim conn As SqlConnection Dim dataSet As New DataSet

Dim adapter As SqlDataAdapter

If ViewState("DepartmentsDataSet") Is Nothing Then

'Read the connection string from Web.config Dim connectionString As String = _

ConfigurationManager.ConnectionStrings( _ "Dorknozzle").ConnectionString

'Initialize connection

conn = New SqlConnection(connectionString) ' Create adapter

adapter = New SqlDataAdapter( _

"SELECT DepartmentID, Department FROM Departments", _ conn)

'Fill the DataSet adapter.Fill(dataSet, "Departments")

'Store the DataSet in view state ViewState("DepartmentsDataSet") = dataSet

Else

dataSet = ViewState("DepartmentsDataSet") End If

' Bind the grid to the DataSet departmentsGrid.DataSource = dataSet departmentsGrid.DataBind()

End Sub

507

Chapter 12: Advanced Data Access

C# File: Departments.aspx.cs (excerpt)

private void BindGrid()

{

// Define data objects SqlConnection conn;

DataSet dataSet = new DataSet(); SqlDataAdapter adapter; if(ViewState["DepartmentsDataSet"] == null)

{

//Read the connection string from Web.config string connectionString =

ConfigurationManager.ConnectionStrings[

"Dorknozzle"].ConnectionString;

//Initialize connection

conn = new SqlConnection(connectionString); // Create adapter

adapter = new SqlDataAdapter(

"SELECT DepartmentID, Department FROM Departments", conn);

//Fill the DataSet adapter.Fill(dataSet, "Departments");

//Store the DataSet in view state ViewState["DepartmentsDataSet"] = dataSet;

}

else

{

dataSet = (DataSet)ViewState["DepartmentsDataSet"];

}

// Bind the grid to the DataSet departmentsGrid.DataSource = dataSet; departmentsGrid.DataBind();

}

Here, we’re using the ViewState collection to store our DataSet. The ViewState collection works a lot like the Session collection, except that instead of storing data for access by the entire application, ViewState stores data for just this one page while the user is interacting with it. If the users navigate away from this page, the data in ViewState will be lost—even if they return to the page within the same session.

In this revised version of BindGrid, we start by checking the ViewState collection for an item named DepartmentsDataSet. If no such item exists, we create a new DataSet, fill it with data from the database, as before, and store it in ViewState. If an item named DepartmentsDataSet does exist in ViewState, we simply save

508