错误显示对象引用未设置为对象的实例?

时间:2012-09-03 10:04:51

标签: c# .net

我是c#和Web服务的新手...... 当我调试登录编码时,它在浏览器上运行,但是当输入登录按钮时,它显示错误对象引用未设置为具有源错误的对象实例,如下所示:

{

   SqlConnection DBConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"].ConnectionString);
    try
    {

是否有任何语法缺失或与数据库的错误连接?

3 个答案:

答案 0 :(得分:1)

您没有名称为ASPNETDBConnectionString的连接字符串,这就是您收到此错误的原因。 使用前请与null核对。

if(System.Configuration.ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"] != null)
         SqlConnection DBConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"].ConnectionString);

答案 1 :(得分:0)

1在System.Configuration上添加引用

2验证App.Config或Web.Config中是否存在ASPNETDBConnectionString字符串连接

Nota:您必须在config

文件中使用此部分ASPNETDBConnectionString
<connectionStrings>
  <add 
    name="ASPNETDBConnectionString" 
    connectionString="Data Source=serverName;Initial 
    Catalog=...;Persist Security Info=True;User 
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>

答案 2 :(得分:0)

firstly add connection string to web config file as follows:

***<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <connectionStrings>
        <add name="key" connectionString="....." providerName="System.Data.SqlClient"/>
    </connectionStrings>
    </configuration>***

then add namespace to .cs page 

> using System.Configuration;


then create a connection string on page as:-
 ***cn = new SqlConnection();
        cn.ConnectionString = ConfigurationManager.ConnectionStrings["key"].ConnectionString;***