0

I have this code in Generic Handler to connect to database and retrieve the image from table,

But when user logging on will choose the database, for example:

my database is: SH001

user: username

Password: password

I save the database in Session["db"] when logging in

and when the user go to products page and searching for products...it list the products with their images...

but since I changed the connection from:

System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection("Data Source=DVR;DataBase=SH001;User ID=userid;Password=password");

to:

System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection("Data Source=DVR;DataBase=" + HttpContext.Current.Session["db"] + ";User ID=userid;Password=password");

it starts to give me an error when retreive the image in products page

Object reference not set to an instance of an object.

this is the code in the Generic Handler:

public class image : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {

        System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection("Data Source=DVR;DataBase=" + HttpContext.Current.Session["db"] + ";User ID=userid;Password=pass");
        string image = context.Request.QueryString["ID"].ToString();
        SqlCommand com = new SqlCommand("Select Image from Products where ID = '" + image + "'", Con);
        Con.Open();

        SqlDataReader Reader = com.ExecuteReader();
        while (Reader.Read())
        {
            if (Reader.GetValue(0) != DBNull.Value)
            {
                context.Response.BinaryWrite((byte[])Reader["Image"]);
            }
        }
        Con.Close();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
Yaser
  • 87
  • 2
  • 9
  • possible duplicate of [ASP.NET: How to access Session from handler?](http://stackoverflow.com/questions/1058568/asp-net-how-to-access-session-from-handler) – Howli May 24 '14 at 21:43
  • You need to do some extra work to access the Session from the handler. See this answer: http://stackoverflow.com/questions/1058568/asp-net-how-to-access-session-from-handler – Brendan Green Apr 30 '14 at 01:32

0 Answers0