Forum Moderators: open
How can I code the site so that if an empty dataset is returned it will truncate the query string of numbers and letters they submitted by one place and resubmit that new string until a dataset is returned with a match. I'm pretty sure id speak your glory to all future generations if you could help me with this. Thanks for any help.
it's C# ASP.Net, but I think you should have a pretty easy time converting the basic logic..
Have fun!
-Mark
if(txtSearchCriteria.Text.Trim().Length > 0)
{
int searchLen = 0;
string searchCriteria = txtSearchCriteria.Text.Trim();
string queryBase = "SELECT * FROM Authors WHERE au_lname like ";
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["Site.Default.ConnectionString"]);
SqlCommand cmd = new SqlCommand(queryBase + "'" + searchCriteria + "%'", con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
searchLen = searchCriteria.Length - 1;
while( (! dr.HasRows) && searchCriteria.Length > 0 )
{
Response.Write(searchCriteria + "<BR>");
Response.Flush();
con.Close();
con.Open();
dr = cmd.ExecuteReader();
searchCriteria = searchCriteria.Substring(0, searchLen);
cmd.CommandText = queryBase + "'" + searchCriteria + "%'";
searchLen -= 1;
}
grdSearchResults.DataSource = dr;
grdSearchResults.DataBind();
con.Close();
}
You need to test for empty resultset, then trim 1 character off the search string :
newSearch = left(strSearch,len(strSearch)-1)
then repeat until a match is found or the search string is 0 characters long.
This logic would be better handled by an SQL stored procedure to reduce trips to and from the server.