简体   繁体   中英

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:

{

   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. Check it against null before using it.

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

1 Add reference on System.Configuration

2 Verify that ASPNETDBConnectionString string connection exist in your App.Config, or your Web.Config

Nota : you must have this section ASPNETDBConnectionString in your file of config

<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;***

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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