1
I’m having difficulties in returning a query in the database using SqlDataAdapter with parameters.
Well, I have a layered application in my View when I first access a GridView with a query (this part is ok)!
In this same View has a field to search and filter in this same GridView, updating it with this filtering, and that uses the same method. Then that gives the error, I used some examples that I found on the net but not working.
When it enters the line in the if that has the following code, enter the catch:
adapter.SelectCommand.Parameters.Add(new SqlParameter("@nome", pessoa.Nome));
The error reported in catch is as follows:
{System.NullReferenceException: Referência de objeto não definida para uma instância de um objeto.}
How could I add this parameter the right way?
Follows the code:
public DataTable listarPessoas(PessoaModel pessoa = null)
{
    try
    {
        conectar();
        queryString = "SELECT * FROM [crud].[dbo].[Pessoas]";
        if (pessoa.Nome != null)
            queryString += " WHERE pess_nome LIKE '%@nome%'";
        SqlCommand sqlCmd = new SqlCommand(queryString, conn);
        DataSet ds = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter();
        if (pessoa.Nome != null)
            adapter.SelectCommand.Parameters.Add(new SqlParameter("@nome", pessoa.Nome));
        conn.Open();
        adapter.SelectCommand = sqlCmd;
        adapter.Fill(ds);
        DataTable dt = ds.Tables[0];
        return dt;
    }
    catch (Exception erro)
    {
        throw erro;
    }
    finally
    {
        conn.Close();
    }
}
Vlw @Fernando, I didn’t even see your answer. I was able to solve, but I’ll give a +1.
– LeoFelipe