The object reference was not defined as an instance of an object

1

You are giving this error:

  

error: "The object reference was not defined as an instance of an object."

In this line of code:

public static string BDConnectionString = 
ConfigurationManager.ConnectionStrings["connString"].ConnectionString;

I do not understand why this is giving error, class where the line of code is:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

/// <summary>
/// Descrição resumida de AcessoDados
/// </summary>
public class AcessoDados
{

    #region Propriedades Publicas
        //"link" para  a base de dados
        String connString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\bd1.mdf;Integrated Security=True";

    public static string BDConnectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;

    #endregion 
    public static SqlCommand CriarLigacaoSQL()
    {
        //criar um SQLConnection com a connString
        SqlConnection connection = new SqlConnection(BDConnectionString);

        //criar um SQLComand com a connection criada
        SqlCommand command = connection.CreateCommand();

        //devolver o resultado do command
        return command;
    }

    public static DataTable ExecuteReader(SqlCommand command)
    {
        //criar uma tabela e iguala a null para mais tarde guardar o resultado
        DataTable table = null;

        try
        {
            //verificar se o SQLCommand passado por parametro tem um ligação aberta
            if(command.Connection.State != ConnectionState.Open)
            {
                //como a ligação nao esta aberta agora vai abrila 
                command.Connection.Open();
            }
            //executar o comando sql e quardar o comando na query criada 
            using(SqlDataReader reader = command.ExecuteReader())
            {
                table = new DataTable();//inicia uma data table 
                table.Load(reader);//preenche a table com os resultados da query
            }

        }
        finally
        {
            TerminarLigacao(command);
        }

        //devolve o resultado da query guardado nao table
        return table;
    }

    public static int ExecuteNonQuery(SqlCommand command)
    {
        //criar uma variavel que ira returnar o numero de linhas afetadas pela query sql
        int linhasAfetadas = -1;
        try
        {
            //verificar se o SQLCommand passado por parametro tem um ligação aberta
            if (command.Connection.State != ConnectionState.Open)
            {
                //como a ligação nao esta aberta agora vai abrila 
                command.Connection.Open();
            }
            linhasAfetadas = command.ExecuteNonQuery();
        }
        finally
        {
            TerminarLigacao(command);
        }

        //devolver o numero de linhas afetadas
        return linhasAfetadas;
    }

    private static void TerminarLigacao(SqlCommand command)
    {
        command.Connection.Close();
        command.Connection.Dispose();
        command.Dispose();
    }

    public AcessoDados()
    {
        //
        // TODO: Adicionar lógica do construtor aqui
        //
    }
}
    
asked by anonymous 19.01.2018 / 17:22

1 answer

0

Either you get the connection string from your web.config , or you set it in your class.

The error happens because you do not have your connection string set on your web.config .

<connectionStrings>
    <add name="connString" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\bd1.mdf;Integrated Security=True" />
  </connectionStrings>

This way, you can get the connection string as follows

ConfigurationManager.ConnectionStrings["connString"].ConnectionString;

No need to set your String connString variable. If you still want to use the variable connString , instead of taking web.config , you pass SqlConnection to connString ( new SqlConnection(connString); ) and remove BDConnectionString

    
19.01.2018 / 17:53