I am building a library management software and im trying to search books by name. However when I try to use what Ive implemented nothing gets returned.
This is the code behind used to retrieve data from the db.
string constr = ConfigurationManager.ConnectionStrings["LibraryContext"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
using (SqlCommand cmd = new SqlCommand())
string bookTitle = Request.QueryString["BookTitle"];
cmd.CommandText = "SELECT * FROM Books WHERE Title LIKE '%@Title%'";
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
DataTable dt = new DataTable();
lvCustomers.DataSource = dt;
Thank you for you help
Do not put quotes around your parameter
cmd.CommandText = "SELECT * FROM Books WHERE Title LIKE %@Title%";
Quotes aroud the parameters tranform everything inside them to a literal string and of course I suppose that you don't have any book whose title is literally "%@Title%"
also I prefer to use a
cmd.CommandText = "SELECT * FROM Books WHERE Title LIKE @Title"; cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = "%" + bookTitle + "%");
AddWithValue is a shortcut with numerous drawback that you need to aware of before trying to use it: Can we stop to use AddWithValue already?