The ASP.NET Session
object can store any (serializable) object running in the CLR. That
goes for larger data—not just small strings or other scalar types. One
of the most common uses for the Session object is for implementing features such as shopping
carts or any other data that has to go with a particular client. For
example, in a commerce-oriented site where customers can purchase
products, you would probably implement a central database representing
your inventory. Then, as users sign on, they have the opportunity to
select items from your inventory and place them in a temporary holding
area associated with the session they're running. In ASP.NET, that
holding area is typically the Session object.
A number of different
collections are useful for managing shopping cart–like scenarios.
Probably the easiest to use is the good ole ArrayList, an automatically sizing array that supports both random access and the IList interface. However, for other scenarios you might use a small DataTable, a DataSet, or some other more complex type. Keep in mind that DataTable and DataSet have more features than necessary for some situations, which could lead to bloated session state if you're not careful.
You also work with the DataTable in depth. The example illustrates using ADO.NET objects, data-bound controls, and session state to transfer items from an inventory (represented as a DataList) to a collection of selected items (represented as a GridView).
Using session state, ADO.NET objects, and data-bound controls
Create a new page on the SessionState site named UseDataList.aspx.
Add DataList to the page by copying the following code between the <div> tags on the generated page. The DataList will display the elements in the .NET References .
<asp:DataList ID="DataList1"
runat="server" BackColor="White" BorderColor="#E7E7FF"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Horizontal"
Style="z-index: 100; left: 8px; position: absolute; top: 16px"
OnItemCommand="DataList1_ItemCommand" Caption="Items in Inventory" >
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<SelectedItemStyle BackColor="#738A9C"
Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingItemStyle BackColor="#F7F7F7" />
<ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<ItemTemplate>
ID:
<asp:Label ID="IDLabel"
runat="server" Text='<%# Eval("ID") %>'></asp:Label><br />
Title:
<asp:Label ID="TitleLabel"
runat="server" Text='<%# Eval("Title") %>'></asp:Label><br />
AuthorLastName:
<asp:Label ID="AuthorLastNameLabel"
runat="server" Text='<%# Eval("AuthorLastName")
%>'></asp:Label><br />
AuthorFirstName:
<asp:Label ID="AuthorFirstNameLabel"
runat="server" Text='<%# Eval("AuthorFirstName")
%>'></asp:Label><br />
Topic:
<asp:Label ID="TopicLabel" runat="server"
Text='<%# Eval("Topic") %>'></asp:Label><br />
Publisher:
<asp:Label ID="PublisherLabel"
runat="server"
Text='<%# Eval("Publisher") %>'></asp:Label><br />
<br />
<asp:Button ID="SelectItem"
runat="server" Text="Select Item" />
</ItemTemplate>
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True"
ForeColor="#F7F7F7" />
</asp:DataList>
The Microsoft Visual Studio Designer should appear like this when you finish:
Stub out a shell for the Select Item button on the ItemCommand handler. Select DataList1
on the page. Look at the Properties pane in Visual Studio. Click the
lightning bolt button to view the available events you can handle. In
the edit box next to the ItemCommand event, notice the name of the command: DataList1_ItemCommand. Double-click inside the edit box and Visual Studio will produce an item command handler. The button's handler will be named DataList1_ItemCommand to match the identifier in the DataList1. You use it shortly to move items from the inventory to the selected items table.
public partial class UseDataList : System.Web.UI.Page
{
protected void DataList1_ItemCommand(object source,
DataListCommandEventArgs e)
{
}
}
Go back to the code for the page and add some code to open a database and populate the DataList. Name the function GetInventory. The example that comes with this book includes a SQL Server database named AspNetStepByStep4 that will work. Add the database to the App_Data folder of this project. You can obtain the
connection string by viewing the database in Server Explorer after you
have added it to the project. You can find the connection string in the
Properties pane after you select the database in Server Explorer.
using System.Data;
Using System.Data.Common;
public partial class UseDataList : System.Web.UI.Page
{
protected DataTable GetInventory()
{
string strConnection =
@"Data Source=
.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\ASPNETStepByStep4.mdf;
Integrated Security=True;
User Instance=True";
DbProviderFactory f =
DbProviderFactories.GetFactory("System.Data.SqlClient");
DataTable dt = new DataTable();
using (DbConnection connection = f.CreateConnection())
{
connection.ConnectionString = strConnection;
connection.Open();
DbCommand command = f.CreateCommand();
command.CommandText = "Select * from DotNetReferences";
command.Connection = connection;
IDataReader reader = command.ExecuteReader();
dt.Load(reader);
reader.Close();
connection.Close();
}
return dt;
}
protected DataTable BindToinventory()
{
DataTable dt;
dt = this.GetInventory();
this.DataList1.DataSource = dt;
this.DataBind();
return dt;
}
// More goes here...
}
Now add a method named CreateSelectedItemsData. This is a table into which selected items are placed. The method takes a DataTable object that describes the schema of the data in the live database (you see how to get that soon). You can create an empty DataTable by constructing it and then adding Columns to the column collection. The schema coming from the database will have the column name and the data type.
public partial class UseDataList : System.Web.UI.Page
{
protected DataTable CreateSelectedItemsTable(DataTable tableSchema)
{
DataTable tableSelectedItemsData = new DataTable();
foreach(DataColumn dc in tableSchema.Columns)
{
tableSelectedItemsData.Columns.Add(dc.ColumnName,
dc.DataType);
}
return tableSelectedItemsData;
}
}
Add code to the Page_Load handler. When the initial request to a page is made (that is, if the request is not a postback), Page_Load should call BindToInventory, which returns the DataTable snapshot of the DotNetReferences table. Use the DataTable as the schema on which to base the selected items table. That is, declare an instance of a DataTable and assign it the result of CreateSelectedItemsTable. Then, store the (now empty) table in the Session object using the key tableSelectedItems.
public partial class UseDataList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = BindToinventory();
DataTable tableSelectedItems =
this.CreateSelectedItemsTable(dt);
Session["tableSelectedItems"] = tableSelectedItems;
}
}
}
Browse to the Web site to make sure that the database connects. It should look something like this:
Now add a GridView
to the page. It represents the table of selected items held in session
state. Don't bother to give it a data source. You add that shortly. Make
sure the AutoGenerateColumns property is set to true. The page appears this way because it's using absolute positioning:
Finally, complete the handler for the SelectItem
button. This method should move items from the inventory to the
selected items table. You can get the selected item index from the DataListCommandEventArgs coming into the handler. Call BindToInventory to set up the DataList
data source so that you can fetch the selected item. You can access the
columns in the selected row using ordinal indices. From the values in
each column, construct a new DataRow
and add it to the selected items table. Store the modified table back
in session state. Finally, apply the new selected items table to the DataSource in the GridView1 and bind the GridView1.
public partial class UseDataList : System.Web.UI.Page
{
protected void DataList1_ItemCommand(object source,
DataListCommandEventArgs e)
{
int nItemIndex = e.Item.ItemIndex;
this.DataList1.SelectedIndex = nItemIndex;
BindToinventory();
// Order of the columns is:
// ID, Title, FirstName, LastName, Topic, Publisher
DataTable dt = (DataTable)DataList1.DataSource;
String strID = (dt.Rows[nItemIndex][0]).ToString();
String strTitle = (dt.Rows[nItemIndex][1]).ToString();
String strAuthorLastName = (dt.Rows[nItemIndex][2]).ToString();
String strAuthorFirstName = (dt.Rows[nItemIndex][3]).ToString();
String strTopic = (dt.Rows[nItemIndex][4]).ToString();
String strPublisher = (dt.Rows[nItemIndex][5]).ToString();
DataTable tableSelectedItems;
tableSelectedItems = (DataTable)Session["tableSelectedItems"];
DataRow dr = tableSelectedItems.NewRow();
dr[0] = strID;
dr[1] = strTitle;
dr[2] = strAuthorLastName;
dr[3] = strAuthorFirstName;
dr[4] = strTopic;
dr[5] = strPublisher;
tableSelectedItems.Rows.Add(dr);
Session["tableSelectedItems"] = tableSelectedItems;
this.GridView1.DataSource = tableSelectedItems;
this.GridView1.DataBind();
}
}
Run
the site. When the page first appears, you should see only the
inventory list on the left side of the page. Click the Select Item
button on some of the items. You should see your browser post back to
the server and render the DataList and the GridView with each newly added selected item.
Now you have a working
application that uses session state. Next, look at the different ways in
which you can configure ASP.NET session state.