I'm having difficulty returning a query in the database using SqlDataAdapter
with parameters.
Well, I have a layered application in my View when I first access feed a GridView
with a query (this part is ok)!
In this same View you have a field to search and filter in this same GridView
, updating it with this filtering, and using the same method. So that gives the error, I used some examples that I found in the net but it is not working.
When you enter the line inside the if
that has the following code, enter 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 correctly?
Follow 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();
}
}