I have a method where I need to return the ID ( integer
) of a particular record whose name passes as a parameter, however Visual Studio points to the following error:
Object reference not set to an instance of an object
This error occurs in the commented line:
public int buscarIdPorNome(string nomeSetor) //Busca id do setor pelo nome
{
int idSetor = 0;
con = dal.conectar();//Conectando com o BD - retorna "new SqlConnection(connectionStringBuilder.ToString());"
string cmdText = "SELECT (ID_Setor) FROM dbo.Setor WHERE Nome_STOR = @Nome_STOR"; //Definindo comando
SqlCommand cmd = new SqlCommand(cmdText, con); //Adicionando comando
cmd.Parameters.AddWithValue("@Nome_STOR", nomeSetor);
con.Open();
idSetor = (Int32)cmd.ExecuteScalar(); //Dando erro
if (con != null)
{
con.Close(); //Fechando conexão
}
return idSetor;
}
I have tried to change the code that is giving error, but I did not succeed, it still points to the same error. Command I tried:
idSetor = int.Parse(cmd.ExecuteScalar().ToString());
Remembering that the object con
is a SQLConnection
and the dal.conectar();
method is only creating StringBuilder
, setting the server and the database, but I do not think it's relevant for this error to put the code here.