I have an ASP.net C# site. I feed one of the ListView in that with this code and it's work:
protected void BindData()
{
string forwardedSearchText = Request.QueryString["SearchText"];
string forwardedSearchColumn = Convert.ToString(Session["SearchTitle"]);
string strsql = "Select TbSoore.IdSoore, TbSoore.NameSoore, TbAye.NumberAye, TbAye.IdAye, TbAye.TextAye, TbAye.TextTarjome From TbAye INNER JOIN TbSoore ON TbAye.IdSoore = TbSoore.IdSoore Where FreeText((" + forwardedSearchColumn + "),N' " + forwardedSearchText + "')";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(strcon))
{
using
(SqlCommand cmdSQL = new SqlCommand(strsql, con))
{
con.Open();
ListViewSearchResults.DataSource = cmdSQL.ExecuteReader();
ListViewSearchResults.DataBind();
}
}
}
Now I want to change the query string style for better security to:
$@"Select TbSoore.IdSoore, TbSoore.NameSoore, TbAye.NumberAye, TbAye.IdAye, TbAye.TextAye, TbAye.TextTarjome From TbAye INNER JOIN TbSoore ON TbAye.IdSoore = TbSoore.IdSoore Where FreeText(({forwardedSearchColumn}),N' @forwardedSearchText ')";
So change BindData()
to:
protected void BindData()
{
string forwardedSearchText = Request.QueryString["SearchText"];
string forwardedSearchColumn = Convert.ToString(Session["SearchTitle"]);
string strsql = $@"Select TbSoore.IdSoore, TbSoore.NameSoore, TbAye.NumberAye, TbAye.IdAye, TbAye.TextAye, TbAye.TextTarjome From TbAye INNER JOIN TbSoore ON TbAye.IdSoore = TbSoore.IdSoore Where FreeText(({forwardedSearchColumn}),N' @forwardedSearchText ')";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(strcon))
{
using
(SqlCommand cmdSQL = new SqlCommand(strsql, con))
{
cmdSQL.Parameters.Add("@forwardedSearchText", SqlDbType.NVarChar).Value = forwardedSearchText;
con.Open();
ListViewSearchResults.DataSource = cmdSQL.ExecuteReader();
ListViewSearchResults.DataBind();
}
}
}
But it doesn't work. I don't get any error but the table is empty.
Can any one help me?
This problem was Like this on and has the same answer. Thank AlbertD.Kallal for his complete answer, his answer helped me but my problem solved by this tip:
I do that AlbertD.Kallal said but instead of forwardedSearchText
,I have to use Request.QueryString["SearchText"]
in command.parameters
with "
both sides of .
So the correct code that works, is:
strsql =
$@"Select TbSoore.IdSoore, TbSoore.NameSoore, TbAye.NumberAye, TbAye.IdAye, TbAye.TextAye, TbAye.TextTarjome
From TbAye INNER JOIN TbSoore ON TbAye.IdSoore = TbSoore.IdSoore
Where FreeText(({forwardedSearchColumn}), @forwardedSearchText )";
}
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(strcon))
{
using
(SqlCommand cmdSQL = new SqlCommand(strsql, con))
{
cmdSQL.Parameters.Add("@forwardedSearchText", SqlDbType.NVarChar).Value =
"\"" + Request.QueryString["SearchText"] + "\"";
con.Open();
dt.Load(cmdSQL.ExecuteReader());
}
ListViewSearchResultAye.DataSource = dt;
ListViewSearchResultAye.DataBind();
}