Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET database search

I'm trying to create a search box on my web application, to search by company name in my database, and bind the result to the GridView. Some of the names in the DB are written in uppercase, some are in lowercase, some are mixed.

The query I have written returns result only if I spell the name in the same way that is in the DB, e.g. if I search "companyname" it wont find anything, but "COMPANYNAME" will.

string find = "select idKorisnik, Korisnik_naziv, Pravni_oblik, Web from tblKorisnici where (Korisnik_naziv like '%' + @find +'%' )";

string CS = ConfigurationManager.ConnectionStrings["CRMdbConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand(find, con);
cmd.Parameters.Add("@find", SqlDbType.NVarChar).Value = txtSearch.Text;

con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "Korisnici_naziv");
GridView2.DataSource = ds;
GridView2.DataBind();
con.Close();
like image 554
Mihovil Lalić Avatar asked Mar 23 '26 04:03

Mihovil Lalić


2 Answers

Change this row:

string find = "select idKorisnik, Korisnik_naziv, Pravni_oblik, Web from tblKorisnici where Korisnik_naziv COLLATE Croatian_100_CI_AI like '%' + @find +'%' ";

There is no subquery.

like image 93
Ruslan K. Avatar answered Mar 24 '26 19:03

Ruslan K.


Try adding COLLATE to the column on which your are filtering so that SQL Server performs a case-insensitive collation such as Croatian_100_CI_AI.

SELECT idKorisnik, Korisnik_naziv, Pravni_oblik, Web
FROM
(
  SELECT
    idKorisnik, 
    Korisnik_naziv COLLATE Croatian_100_CI_AI AS Korisnik_naziv,
    Pravni_oblik, 
    Web
  FROM tblKorisnici
)
WHERE Korisnik_naziv LIKE '%' + @find +'%';

Or without the derived table as per Rusian K's answer:

SELECT idKorisnik, Korisnik_naziv, Pravni_oblik, Web
FROM tblKorisnici
WHERE Korisnik_naziv LIKE '%' + @find +'%' COLLATE Croatian_100_CI_AI;
like image 28
Ɖiamond ǤeezeƦ Avatar answered Mar 24 '26 19:03

Ɖiamond ǤeezeƦ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!