Click here to Skip to main content
15,908,437 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello. I get a
System.NullReferenceException: 'Object reference not set to an instance of an object.'
when i try to Load my excel file to my local SQL server. When I launch the app everything is fine. I can choose the file, it appears in the textbox and when i click the Load button I get the
System.NullReferenceException: 'Object reference not set to an instance of an object.'
at the
conString = ConfigurationManager.ConnectionStrings["AkinTest"].ConnectionString;
for .xls files.

I also get this with it:

System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null.


What I have tried:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;


public partial class CS : System.Web.UI.Page
{
protected void Upload(object sender, EventArgs e)
{
    //Upload and save the file
    string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
    FileUpload1.SaveAs(excelPath);

    string conString = string.Empty;
    string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
    switch (extension)
    {
        case ".xls": //Excel 97-03
            conString = ConfigurationManager.ConnectionStrings["AkinTest"].ConnectionString;
            break;
        case ".xlsx": //Excel 07 or higher
            conString = ConfigurationManager.ConnectionStrings["AkinTest"].ConnectionString;
            break;
        case ".csv": //CSV Files
            conString = ConfigurationManager.ConnectionStrings["AkinTest"].ConnectionString;
            break;
                //SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[""].ConnectionString);
                //con.Open();

        }
    conString = string.Format(conString, excelPath);
    using (OleDbConnection excel_con = new OleDbConnection(conString))
    {
        excel_con.Open();
        string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
        DataTable dtExcelData = new DataTable();

        //[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
        dtExcelData.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                new DataColumn("Name", typeof(string)),
                new DataColumn("Salary",typeof(decimal)) });

        using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
        {
            oda.Fill(dtExcelData);
        }
        excel_con.Close();

        string consString = ConfigurationManager.ConnectionStrings["AkinTest"].ConnectionString;
        using (SqlConnection con = new SqlConnection(consString))
        {
            using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
            {
                //Set the database table name
                sqlBulkCopy.DestinationTableName = "dbo.tblPersons";

                //[OPTIONAL]: Map the Excel columns with that of the database table
                sqlBulkCopy.ColumnMappings.Add("Id", "PersonId");
                sqlBulkCopy.ColumnMappings.Add("Name", "Name");
                sqlBulkCopy.ColumnMappings.Add("Salary", "Salary");
                con.Open();
                sqlBulkCopy.WriteToServer(dtExcelData);
                con.Close();
            }
        }
    }
}
}


ASP.NET
<pre><%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button Text="Upload" OnClick = "Upload" runat="server" />
        <br />
        <br />
        <br />
        <br />
    </form>
</body>
</html>
Posted
Updated 12-Nov-19 11:33am

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
Net 3.5 Connection String would be located in your web.config file, similar to this
XML
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
	<connectionStrings>
		<add name="AkinTest" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\PathTo\MyExcelFile.xlsx; Extended Properties=Excel 12.0"; />
	</connectionStrings>
</configuration>
 
Share this answer
 
Comments
Computer Wiz99 14-Nov-19 9:17am    
Hello MadMyche. Thanks for the information. This is what I have:

<configuration>
<connectionstrings>


<add name="AkinTestConnectionString" connectionstring="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'">

MadMyche 14-Nov-19 10:20am    
The names don't match between your code and configuration.

Your web.config has this:
<add name="AkinTestConnectionString" connectionstring="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'">

While your application is looking for
conString = ConfigurationManager.ConnectionStrings["AkinTest"].ConnectionString;
Computer Wiz99 14-Nov-19 13:20pm    
Thanks for the update. I did make the changes. Now when I run the program I get a System.ArgumentException: 'Column 'TABLE_NAME' does not belong to table MetaDataCollections.' and here is where is happens: string sheet1 = excel_con.GetSchema().Rows[0]["TABLE_NAME"].ToString();
MadMyche 14-Nov-19 17:00pm    
You are going to need to look at what your code has and compare that to what is in the spreadsheet

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