sun
sun

Reputation: 85

Object reference not set to an instance of an object when converting

My code is:

Stream strm = ShowEmpImage(empno);

public Stream ShowEmpImage(int empno)
    {

        string conn = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "select Cust_Image from Cust_M_Tbl  where Cust_FID = '"+empno+"'";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        connection.Open();
        object img = cmd.ExecuteScalar();
            try
            {

                return new MemoryStream((byte[])img);    ////Exception generated here

            }
            catch
            {
                return null;
            }
            finally
            {
                connection.Close();
            }

    }

I am using VS2008, C#, ASP.NET 3.5 Framework, SQL Server 2005. Any help will be appreciated. Regards.

Upvotes: 0

Views: 2331

Answers (3)

Renatas M.
Renatas M.

Reputation: 11820

Ok many tries to help you but the problem is unspecified in question. From previous your question I can tell that problem is - field Cust_Image is varchar and you trying to convert it to binary.

So solution should be something like this:

return new MemoryStream(Convert.FromBase64String(img.ToString())); 

Upvotes: 1

Ian Nelson
Ian Nelson

Reputation: 58763

This will occur if no row exists in the database for the specified employee number.

We need to check for this before casting the result to a byte array.

Try this:

public static string ConnectionString = 
    ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;

public Stream ShowEmployeeImage(int employeeNumber)
{
    using (var conn = new SqlConnection(ConnectionString))
    {
        const string query = 
            "select Cust_Image from Cust_M_Tbl where Cust_FID = '@empNo'";

        using (var command = new SqlCommand(query, conn))
        {
            command.Parameters.AddWithValue("@empNo", employeeNumber.ToString());
            conn.Open();

            var image = command.ExecuteScalar();

            return image == null ? null : new MemoryStream((byte[]) image);
        }
    }
}

Upvotes: 0

Azhar Khorasany
Azhar Khorasany

Reputation: 2709

Scenario 1:

string conn = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;

use this line as:

string conn = string.Empty;
if(ConfigurationManager.ConnectionStrings["dbcon"] != null)
{
    conn = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;
}

if you don't set the dbcon key in your app.config file, you can't access ConnectionString property as ConfigurationManager.ConnectionStrings["dbcon"] will give you null.

Scenario 2:

object img = cmd.ExecuteScalar();

Check whether the img object is null before using it in the code.

Upvotes: 0

Related Questions