-2

I am trying to upload files to database but it is giving me an null exception error

Here is the error: System.NullReferenceException: Object reference not set to an instance of an object.

Can anybody help me finding the error:

Here is aspx code

<div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<hr />
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
    AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="File Name"/>
        <asp:TemplateField ItemStyle-HorizontalAlign = "Center">

        </asp:TemplateField>
    </Columns>
</asp:GridView>
    </div>

Here is the code behind:

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

public partial class DatabaseDownload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Upload(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
        string contentType = FileUpload1.PostedFile.ContentType;
        using (Stream fs = FileUpload1.PostedFile.InputStream)
        {
            using (BinaryReader br = new BinaryReader(fs))
            {
                byte[] bytes = br.ReadBytes((Int32)fs.Length);
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string query = "insert into tblFiles values (@Name, @ContentType, @Data)";
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@Name", filename);
                        cmd.Parameters.AddWithValue("@ContentType", contentType);
                        cmd.Parameters.AddWithValue("@Data", bytes);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
        }
        Response.Redirect(Request.Url.AbsoluteUri);
    }
}
user112647
  • 73
  • 1
  • 2
  • 4
  • Null reference errors are always the same. You are trying to access a property on an object whose value is null. On which line do you receive the error? – crthompson May 27 '14 at 16:36
  • string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; – user112647 May 27 '14 at 16:37
  • So then `ConfigurationManager.ConnectionStrings["constr"]` returns null. Therefore you cannot access `.ConnectionString`. Are you sure that you have a connection string called `constr`? – crthompson May 27 '14 at 16:39
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – crthompson May 27 '14 at 16:41
  • Actually... i think that its `ConfigurationManager` that is returning null. I'm not sure that its static. Where do you declare it? – crthompson May 27 '14 at 16:43
  • Here is my connection string can you help me as where I am making mistake? – user112647 May 27 '14 at 16:44
  • Your name is `DefaultConnection`, not `constr` – crthompson May 27 '14 at 16:46
  • As you debug, drill down into the values that `ConnectionStrings` contains. You'll see the valid values. – crthompson May 27 '14 at 16:47
  • But when I corrected the name of connection string it is still not allowing me to save file in database this it gave this error: Cannot attach the file 'D:\FALL2013\milestone2\WebSite2\App_Data\aspnet-WebSite2(1)-20140521092147.mdf' as database 'aspnet-WebSite2(1)-20140521092147'. – user112647 May 27 '14 at 16:52
  • That sounds like a new question! :) At least its finding the connectionstring. I'd suggest looking at connectionstrings.com to make sure you have the correct string for your scenario. – crthompson May 27 '14 at 16:55

1 Answers1

1

If your connection named as

<add name="DefaultConnection" ...

then you can obtain its value using same key (DefaultConnection)

string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

Now if for some reasons that db does not work (perhaps you delete the DB file, etc) you can try to fixe it by deleting DB. Do this from the command line. Open the "Developer Command Propmpt for VisualStudio" under your "Start/Programs menu->All Programs->Visual Studio 2012->Visual Studio Tools"

Run the following commands:

sqllocaldb.exe stop v11.0
sqllocaldb.exe delete v11.0

Now execute "update-database" command from package manager console and it will create database for you without any obstacles.

user2316116
  • 6,726
  • 1
  • 21
  • 35