System.Nullreferenceexception: Undefined object reference for an instance of an object

Asked

Viewed 623 times

1

I am developing a project in Asp.net, where I am trying to carry out this insertion in the bank. However when I try to perform this command, I end up stating this error message: "System.Nullreferenceexception: Object reference not set to an instance of an object."

[WebMethod]
public void InsertUsuario(string usuario, string senha, string nome, string dtnasc, string fone, string email, int oab, string endereco, string bairro, string cep, int codcidade, string cpf, string cnpj)
{
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            {
                string chav = "asfasdf";
                DateTime dateFromString = DateTime.Parse(dtnasc, System.Globalization.CultureInfo.InvariantCulture);
                SqlCommand command = new SqlCommand("INSERT Into Usuarios (IdUsuario, Usuario, Senha, Nome, Chave, DtNasc, Fone, Email, OAB, Endereco, Bairro, CEP, CodCidade, CPF, CNPJ) VALUES ((Select MAX(idusuario)+1 from Usuarios), '" + usuario + "', '" + senha + "', '" + nome + "', '" + chav + "', '"+dateFromString+"', '" + fone + "', '" + email + "', " + oab + ", '" + endereco + "', '" + bairro + "', '" + cep + "', " + codcidade + ", '" + cpf  + "','"+cnpj+"')");
                Console.WriteLine(dateFromString.ToString());
                conn.Open();
                command.ExecuteNonQuery();

            }
}

This is the bank created:

Create table Usuarios (
IdUsuario              int  not null,
Usuario                varchar(30) not null,
Senha                  varchar(30) not null,
Nome                   varchar(50) not null,
Chave                  varchar(18) not null,
DtNasc                 date null,
Fone                   varchar(15) not null,
Email                  varchar(70) null,
OAB                    int null,
Endereco               varchar (100) null,
Bairro                 varchar (80) null,
CEP                    varchar (9) null,
CodCidade              int null,
CPF                    varchar (20) null,
CNPJ                   varchar (20) null
primary key (IdUsuario)
)

Error message:

System.InvalidOperationException: ExecuteNonQuery: propriedade Connection não foi inicializada. em System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) em System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(Tas‌​kCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) em System.Data.SqlClient.SqlCommand.ExecuteNonQuery() 
  • in your web.config declared the string ?

  • I declared yes, I have done other tests in the bank and the connection is working correctly.

  • on which line exactly the error occurs ?

  • Then it does not say which line is the error: System.Nullreferenceexception: Referência of object não defined for an Instância of an object. in Onipresenteapi.oni.Insertusuario(String user, String password, String name, String dtnasc, String fone, String email, Int32 oab, String address, String neighborhood, String cep, Int32 codcity, String Cpf, String cnpj) this is the complete error message

  • print with error image ?

1 answer

0

You are not assigning the connection to command,

try to do so:

string sql = @"INSERT Into Usuarios (IdUsuario, Usuario, Senha, Nome, Chave, DtNasc, Fone, Email, OAB, Endereco, Bairro, CEP, CodCidade, CPF, CNPJ) VALUES ((Select MAX(idusuario)+1 from Usuarios), '" + usuario + "', '" + senha + "', '" + nome + "', '" + chav + "', '"+dateFromString+"', '" + fone + "', '" + email + "', " + oab + ", '" + endereco + "', '" + bairro + "', '" + cep + "', " + codcidade + ", '" + cpf  + "','"+cnpj+"')";


string chav = "asfasdf";
DateTime dateFromString = DateTime.Parse(dtnasc, System.Globalization.CultureInfo.InvariantCulture);
SqlCommand command = new SqlCommand(sql, conn);
Console.WriteLine(dateFromString.ToString());
conn.Open();
command.ExecuteNonQuery();
  • Now displays this message System.Invalidoperationexception: Executenonquery: Connection property nãhas been initialized. 
 em System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
 em System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
 em System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

  • edit your question and put the current code as is

Browser other questions tagged

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