0

我是 C# 和 Web 服务的新手...当我调试它在浏览器上运行的登录编码时,但是当输入登录按钮时,它显示错误 Object reference not set to an instance of an object with source error,如下所示:

{

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

是否存在与数据库连接丢失或错误的语法?

4

3 回答 3

1

您没有带有ASPNETDBConnectionString名称的连接字符串,这就是您收到此错误的原因。在使用它之前检查null它。

if(System.Configuration.ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"] != null)
         SqlConnection DBConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"].ConnectionString);
于 2012-09-03T10:06:38.147 回答
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;***
于 2012-09-03T10:16:46.313 回答
0

1 添加对 System.Configuration 的引用

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

注意:您的配置文件中必须有此部分 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>
于 2012-09-03T10:06:53.560 回答