connectionstring:对象引用未设置为对象实例

时间:2022-01-28 16:55:14

I want to connect with a db with a connectionstring in an application config file but always get this error :

我想在应用程序配置文件中使用带有连接字符串的数据库连接,但始终会收到此错误:

object reference not set to an object instance

对象引用未设置为对象实例

In the first code line with the ConfigurationManger I have checked it several times but I do not think that I have made a mistake. Hope you can find something.

在使用ConfigurationManger的第一个代码行中,我已经多次检查了它,但我认为我没有犯错。希望你能找到一些东西。

Code

string con = ConfigurationManager.ConnectionStrings["dbConnect"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(con))
            {
                SqlDataAdapter adapter = new SqlDataAdapter("Select* From dsds m with (nolock) inner join asdas a with (nolock) on a.id = m.id where  test....., conn);
                ds = new DataTable(" ");
                adapter.Fill(ds);
                dataGridView1.DataSource = ds;

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConnect"
     connectionString="Data Source=test;Initial Catalog=as;Integrated Security=True"
     providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>

1 个解决方案

#1


2  

string con = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnect"].ConnectionString;

Edit:

As you have two app.config, you can either delete one, or if you want to control programatically which app.config to use, Refer How can I use several Application Configuration Files in one project?

由于您有两个app.config,您可以删除一个,或者如果您想以编程方式控制要使用的app.config,请参阅如何在一个项目中使用多个应用程序配置文件?

#1


2  

string con = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnect"].ConnectionString;

Edit:

As you have two app.config, you can either delete one, or if you want to control programatically which app.config to use, Refer How can I use several Application Configuration Files in one project?

由于您有两个app.config,您可以删除一个,或者如果您想以编程方式控制要使用的app.config,请参阅如何在一个项目中使用多个应用程序配置文件?