I'm developing a project in asp.net, where I'm trying to do this insertion in the database. But when I try to perform this command, it ends up saying 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 created bank:
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(TaskCompletionSource'1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) em System.Data.SqlClient.SqlCommand.ExecuteNonQuery()