Monday, November 24, 2008

Session State Sample

this is a session state practise:

Default.aspx Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Session State</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>Session State</h1>
<h3>Select a book category</h3>

<asp:RadioButtonList ID="rdl" runat="server" CellPadding="20" RepeatColumns="3" RepeatDirection="Horizontal" OnSelectedIndexChanged="rdl_SelectedIndexChanged">
<asp:ListItem Value="n">.NET</asp:ListItem>
<asp:ListItem Value="d">DataBase</asp:ListItem>
<asp:ListItem Value="h">HardWare</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="btn" runat="server" Text="Submit" onclick="btn_Click" />
<br /><br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<br /><br />
<asp:DropDownList ID="ddl" runat="server" Visible="false"></asp:DropDownList>
</center>
</div>
</form>
</body>
</html>

Default.aspx.cs Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Text;//necessary for StringBuilder

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void rdl_SelectedIndexChanged(object sender, EventArgs e)
{
if (rdl.SelectedIndex != -1)
{
string[] Books = new string[3];
Session["cattext"] = rdl.SelectedItem.Text;
Session["catcode"] = rdl.SelectedItem.Value;

switch (rdl.SelectedItem.Value)
{
case "n":
Books[0] = "Programming C#";
Books[1] = "Programming ASP.NET";
Books[2] = "Programming Essentials";
break;
case "d":
Books[0] = "Oracle & Open Source";
Books[1] = "SQL in a NutShell";
Books[2] = "Transact-SQL Programming";
break;
case "h":
Books[0] = "PC Hardware in a Nutshell";
Books[1] = "Dictionary of PC Hardware and Data Communications Terms";
Books[2] = "Linux Device Drivers";
break;
}

Session["books"] = Books;
}
}
protected void btn_Click(object sender, EventArgs e)
{
if (rdl.SelectedIndex == -1)
{
lblMessage.Text = "You must select a book category.";
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("You have selected the category ");
sb.Append((string)Session["cattext"]);
sb.Append(" with code \"");
sb.Append((string)Session["catcode"]);
sb.Append("\".");
lblMessage.Text = sb.ToString();

ddl.Visible = true;
string[] CatBooks = (string[]) Session["books"];

//populate the DropDownList
ddl.Items.Clear();
for (int i = 0; i < CatBooks.GetLength(0); i++)
{
ddl.Items.Add(new ListItem(CatBooks[i]));
}
}
}
}