views:

230

answers:

3

Hi all,

I trying to save employee image in employee database. I have three field in database table empid, empname, empimage. Here is my database part.

CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)

In the button click event, i have written the following code:

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["EmployeeConnString"].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);
    }
    catch
    {
        lblResult.Text = "There was an error";
    }
    finally
    {
        connection.Close();
    }

And Here is my form:

<asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
    <br />
    <asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:FileUpload ID="imgUpload" runat="server" />
    <br />
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
        onclick="btnSubmit_Click" />   
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp      
    <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
    <br />
    <hr />  
    <asp:Image ID="Image1" style="width:200px" Runat="server" />

But when I am uploading any image and clicking on submit button getting this error "Object reference not set to an instance of an object." Pls somebody point out my error.

Thanks, Sumit

+1  A: 

Object Reference errors only occur when an object is not initialized and you try to reference it. This could be any object you are referencing within your code. If you step through the code while debugging, you can see exactly which reference is null.

You have an if statement that initializes the imgByte object:

  imgByte = new Byte[File.ContentLength];

If the img object turns out to be null, that code does not run. Then you reference the imgByte here, regardless of whether or not the img was null:

  cmd.Parameters.AddWithValue("@eimg", imgByte);

Check the the HttpPostedFile object itself is not null and move your imgByte object initialization outside the if statement. Also, the name File is already used by the System.IO.File object. You may want to rename it just to be safe.

Jtangowski
The Visual Studio debugger has an option to throw you into debug on any .NET exception, even if it's being handled. It's extremely useful, and I run with it set all the time. Under the Debug menu, click on "Exceptions..."
Cylon Cat
A: 

I would rearrange your ADO.NET code a bit - make it safe and more reliable; also, I would make sure to separate the two SQL statements in your "sql" string by a semicolon to make it clear to SQL that this is two commands, really:

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

using(connection = new SqlConnection(conn))
{
     string sqlStmt = "INSERT INTO dbo.EmpDetails(empname, empimg) " + 
                      "VALUES(@enm, @eimg); SELECT @@IDENTITY";

     using(SqlCommand cmd = new SqlCommand(sqlStmt, connection))
     {
        cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
        cmd.Parameters.AddWithValue("@eimg", imgByte);

        connection.Open();

        int id = Convert.ToInt32(cmd.ExecuteScalar());

        connection.Close();

        lblResult.Text = String.Format("Employee ID is {0}", id);
     }
}

Any luck with this?? Otherwise you should really step through the code in the debugger and see where in your code you reference something that is NULL (and you don't check for that condition).

Marc

marc_s
Hi While i am debugging this code i am getting exception in this line..."string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;"Exception is:Object reference not set to an instance of an object.
Sumit
then obviously, you don't have a connection string called "EmployeeConnString" in your app.config or web.config - check that!
marc_s
A: 

While i am debugging this code i am getting exception in this line..."string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;" Exception is: Object reference not set to an instance of an object.

You need to add a connection string named EmployeeConnString to web.config.

Your exception handler does not distinguish where exactly an exception occurred, and issues a single error message for any possible error.

devio