Following the recommendation that @bigown did in this question I decided to parameterize the SQL queries of my program. See:
private void btnConsulta_Click(object sender, EventArgs e)
{
if (optID.Checked) //Consulta por ID
{
if (nmrID.Text == "0" || nmrID.Text == "")
cnxCli.sel = "select * from cliente;";
else
{
cnxCli.sel = "Select * from cliente " +
"WHERE IDCliente = @ID";
cnxCli.selCmd.CommandText = cnxCli.sel;
cnxCli.selCmd.Parameters.Clear();
cnxCli.selCmd.Parameters.Add("@ID", SqlDbType.Int);
cnxCli.selCmd.Parameters["@ID"].Value = nmrID.Text;
}
cnxCli.clienteDataTable.Clear();
cnxCli.clienteAdapter.Fill(cnxCli.clienteDataTable);
gridPrincipal.Update();
}
else if(optNome.Checked)//Consulta por Nome
{
if (txtNome.Text == "")
cnxCli.sel = "select * from cliente";
else
{
cnxCli.sel = "Select * from cliente " +
"WHERE Nome like '%@Nome%'";
cnxCli.selCmd.CommandText = cnxCli.sel;
cnxCli.selCmd.Parameters.Clear();
cnxCli.selCmd.Parameters.Add("@Nome", SqlDbType.Text);
cnxCli.selCmd.Parameters["@Nome"].Value = txtNome.Text;
}
cnxCli.clienteDataTable.Clear();
cnxCli.clienteAdapter.Fill(cnxCli.clienteDataTable);
gridPrincipal.Update();
}
}
It turns out that the code section after else
, which should return all records containing the name related to the @Nome
parameter, returns only one empty table. As you can see the query by ID was done the same way, and it returns the result of the normal select.
I did a check, set a breakpoint just after the line cnxCli.selCmd.Parameters["@Nome"].Value = txtNome.Text;
to check if everything was right.
I have found that cnxCli.selCmd.CommandText
contains the string "Select * from cliente WHERE Nome like '%@Nome%'"
, as expected. I figured then that something wrong happened with the value of the @Nome
parameter. However the value of the parameter was the text found in txtNome.Text
, also as expected.
Then I put the query in SQL Server, figuring that I had mounted like '%%'
wrongly, but everything is normal too.
Where am I going wrong?
EDIT: SOLUTION FOUND
I found a similar problem in Stack Overflow in English.