简体   繁体   English

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

[英]Error shows Object reference not set to an instance of an object?

I am new to c# and web services... when i debug the login coding it run on the browser but when enter the login button it shows error Object reference not set to an instance of an object with the source error as below: 我是C#和Web服务的新手...当我调试登录代码时,它在浏览器上运行,但是当输入登录按钮时,它显示错误对象引用未设置为具有源错误的对象实例,如下所示:

{

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

is there any syntax that missing or error connection with database? 是否有缺少与数据库连接或连接错误的语法?

You don't have a connection string with ASPNETDBConnectionString name, that is why you are getting this error. 您没有名称ASPNETDBConnectionString的连接字符串,这就是为什么出现此错误的原因。 Check it against null before using it. 在使用前请检查是否为null

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

1 Add reference on System.Configuration 1在System.Configuration上添加引用

2 Verify that ASPNETDBConnectionString string connection exist in your App.Config, or your Web.Config 2验证您的App.Config或Web.Config中是否存在ASPNETDBConnectionString字符串连接

Nota : you must have this section ASPNETDBConnectionString in your file of config 注意:您的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>
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;***

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM