Object reference is not defined as an instance of an object

Asked

Viewed 1,171 times

1

You’re making this mistake:

error:"Object reference is not defined as an instance of an object."

On this code line:

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

I do not understand why this to give error, class where this the line of code:

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
        //
    }
}
  • 1

    Checks whether the Web.Config/App.Config has the setting of Connection strings with key=connString

  • Posta his App.Config ai.

1 answer

0


Or you take your connection chain web.config, or you set her in your class.

The error happens because you don’t have your connection string defined in 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 take the connection string as follows

ConfigurationManager.ConnectionStrings["connString"].ConnectionString;

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.