Hi Everyone

I'm using ASP.NET with C# for an application. I want to know how to take values from a database(sqlserver) and store it in session variables in .net. Can anyone pl help?

Thanks in Advance

u just write a select statement for the table u need to assign session .
using a dataset or dataadapter retrieve the data and assign the data to the session

Use ADO.NET to get data from the database.

I recommend you create a custom class that has a property for each of the data columns. Iterate the database resultset (be it a SqlDataReader or DataTable or whatever) and create an array of your custom class. One per record. Assign the array to the Session.

You could of course just bung the disconnected DataTable or DataSet straight into the session variable. But, they don't serialize very efficiently. I would not recommend this approach if your application has a lot of users say more than 25.

add using System.Data.SqlClient;
and add following table data

int CustomerID;
string CompanyName;
SqlConnection con = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");
SqlCommand cmd = new SqlCommand("SELECT CustomerID, CompanyName FROM Customers", con);
cmd.CommandTimeout = 30;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "Customers");
if (ds != null)
DataTable dt = ds.Tables[0];
if (dt != null)
DataRow dr = dt.Rows[0];
if (dr["CustomerID"].ToString() != "")
CustomerID = int.Parse(dr["CustomerID"].ToString());
if (dr["CompanyName"].ToString() != "")
CompanyName = dr["CompanyName"].ToString();
catch (Exception)

Edited 3 Years Ago by happygeek: fixed formatting

This article has been dead for over six months. Start a new discussion instead.