Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I am trying to fetch a image from MS SQL DB. GetEmpImg() is getting called by in other class, i want return the bytes data. but return code is not reachable my code snippet:

public static byte[] GetEmpImg(int emp_no)
        {
            byte[] empImgBytes;
            AdoHelper.ConnectionString = ConfigurationManager.ConnectionStrings["imageconst"].ConnectionString;
            string query = "select EmpPhoto from EmpPhoto where EmpNo=@empno";

            using (AdoHelper adoHelper = new AdoHelper())
            using (SqlDataReader dataReader = adoHelper.ExecDataReader(query, "@empno", emp_no))
            {
                if (dataReader.FieldCount > 0)
                {
                    while (dataReader.Read())
                    {
                        empImgBytes = (byte[])dataReader["EmpPhoto"];
                        return empImgBytes; ///here im getting the data but ImgBytes not reachable outside of this scope
                    }
                }
                dataReader.Close();
                return imagebytesdata;////here i want return the image bytes
            }
            
        }


What I have tried:

I am getting the data from SqlDataReader then assigning it a variable. but not able to return the code.
Posted
Updated 5-Nov-20 20:05pm

1 solution

You can't return byte data there: it doesn't exist, because you haven't read it.

You only read any data when there is at least one row available - and there should be only one row, so the while loop is redundant, just use an if instead - and when you have retrieved it you immediately return it to the caller. So what data do you expect to be available to return if there are no rows as a result of the query?

What you are asking for is "if there is no such employee, return his picture". Which is clearly nonsense!

Instead, either return an empty array, or return nulland let the calling method figure out what it wants to do with the problem!

C#
public static byte[] GetEmpImg(int emp_no)
    {
    byte[] empImgBytes = null;
    AdoHelper.ConnectionString = ConfigurationManager.ConnectionStrings["imageconst"].ConnectionString;
    string query = "SELECT EmpPhoto FROM EmpPhoto WHERE EmpNo=@EMPNO";

    using (AdoHelper adoHelper = new AdoHelper())
        {
        using (SqlDataReader dataReader = adoHelper.ExecDataReader(query, "@EMPNO", emp_no))
            {
            if (dataReader.Read())
                {
                empImgBytes = (byte[])dataReader["EmpPhoto"];
                }
            }
        }
    return empImgBytes;
    }
 
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