Click here to Skip to main content
15,917,862 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i want retrieve picture in web via ASP.NET from DB,when I run my website ,I receive bellow error from connection.close(),
Object reference not set to an instance of an object.
please help me
my codes are:
C#
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection connection = null;
        try
        {
            FileUpload img = (FileUpload)imgUpload;
            Byte[] imgByte = null;
            if (img.HasFile && img.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = imgUpload.PostedFile;
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            // Insert the employee name and image into db
            string conn = ConfigurationManager.ConnectionStrings["Data Source=.;Initial Catalog=Employee;Integrated Security=True"].ConnectionString;
            connection = new SqlConnection(conn);

            connection.Open();
            string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
            cmd.Parameters.AddWithValue("@eimg", imgByte);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            lblResult.Text = String.Format("Employee ID is {0}", id);
            Image1.ImageUrl = "~/Handler.ashx?id=" + id;
        }
        catch
        {
            lblResult.Text = "There was an error";
        }
        finally
        {
            connection.Close();
        }
        
    }

and in handler I wrote;
C#
%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class Handler : IHttpHandler {
    
    public void ProcessRequest(HttpContext context)
    {
       Int32 empno;
       if (context.Request.QueryString["id"] != null)
            empno = Convert.ToInt32(context.Request.QueryString["id"]);
       else
            throw new ArgumentException("No parameter specified");
 
       context.Response.ContentType = "image/jpeg";
       Stream strm = ShowEmpImage(empno);
       byte[] buffer = new byte[4096];
       int byteSeq = strm.Read(buffer, 0, 4096);
 
       while (byteSeq > 0)
       {
           context.Response.OutputStream.Write(buffer, 0, byteSeq);
           byteSeq = strm.Read(buffer, 0, 4096);
       }        
       //context.Response.BinaryWrite(buffer);
    }
 
    public Stream ShowEmpImage(int empno)
    {
 string conn = ConfigurationManager.ConnectionStrings     ["EmployeeConnString"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
        SqlCommand cmd = new SqlCommand(sql,connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        connection.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])img);
        }
        catch 
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
 
 
}
Posted
Updated 16-Jun-12 19:01pm
v2

Object reference not set to an instance of an object
This error happens when you try to use a property or call a method of an object that is null. More details: here[^]

A simple use of Visual studio DEBUGGER can tell you the object because of which it is happening. Just look at the stack trace and put a debugger on that line. Check the objects of that line and see if any one is null and you are trying to use that objects property. Handle the same.

If you say, it is happening at connection.Close() line then it means that connection object is null then.
 
Share this answer
 
If you get an error between the try and the line:
C#
connection = new SqlConnection(conn);

then connection will be null in the finalise section. Either move the assignment to earlier in the method, or check for both null and open in the finalise before you call Close.

Preferably, do both - it is somewhat more defensive coding.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900