问题
I have a simple WinForm that I'm using to try to help me with ADO.NET. It has a datagridview
I have added a compact sql server database to the project called experiment.sdf
In the App.config file I have added the following. I used a previous project app file to base this on so maybe there's an error in here?:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="DatabaseDGVexperiments.Properties.Settings.DatabaseDGVexperimentsConnStg"
connectionString="Data Source=|DataDirectory|\experiment.sdf"
providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
</configuration>
I've added a reference to the configuration library.
Behind the form is the following code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseDGVexperimentsConnStg"].ConnectionString);
When it hits the line SqlConnection conn = ...
I get an error NullReferenceException was unhandled
. How do I fix this?
回答1:
Change this:
name="DatabaseDGVexperiments.Properties.Settings.DatabaseDGVexperimentsConnStg"
to:
name="DatabaseDGVexperimentsConnStg"
or change this:
ConfigurationManager.ConnectionStrings["DatabaseDGVexperimentsConnStg"]
to:
ConfigurationManager.ConnectionStrings["DatabaseDGVexperiments.Properties.Settings.DatabaseDGVexperimentsConnStg"]
回答2:
ConfigurationManager.ConnectionStrings["DatabaseDGVexperiments.Properties.Settings.DatabaseDGVexperimentsConnStg"].ConnectionString
note that you need to give name as
DatabaseDGVexperiments.Properties.Settings.DatabaseDGVexperimentsConnStg
not as
DatabaseDGVexperimentsConnStg
EDIT:
You need to use SqlCeConnection
and SqlCeDataAdapter
too work with SqlServerCe database, add reference to System.Data.SqlServerCe
and then code should like below.
using (var conn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["DatabaseDGVexperiments.Properties.Settings.DatabaseDGVexperimentsConnStg"].ConnectionString))
{
conn.Open();
using (var myAdapt = new SqlCeDataAdapter("SELECT * FROM experiment.dbo.helloworld", conn))
{
DataSet mySet = new DataSet();
myAdapt.Fill(mySet, "AvailableValues");
DataTable myTable = mySet.Tables["AvailableValues"];
this.uxExperimentDGV.DataSource = myTable;
}
}
回答3:
You've used a different key value in your code then in web.config. the strings need to match exactly.
来源:https://stackoverflow.com/questions/10961348/very-simple-c-sharp-program-generates-a-nullreferenceexception-was-unhandled-e