Wild Card Searching -

Nov 5 2004 7:34 AM
Hello I am new to C# and am trying to build wildcard searching into my dynamic SQL search criteria. I think I may be straying down the wrong path and wanted some help to see if there is an easier way to write this. I obviosuly need to have some validation in there too to make sure someone doesn't enter stuff like smit%xyz =========================== string strForename = txtForename.Text.ToUpper(); string strSurname = txtSurname.Text.ToUpper(); //Check for % wildcard int intWildF = strForename.IndexOf("%",0); int intWildS = strSurname.IndexOf("%",0); if (strForename.Length != 0) if (intWildF != -1) { strForename = strForename.Substring(0, intWildF); strSQLWhere += "AND UPPER(p.FORENAME) LIKE " + UseWildCards(strForename); } else { strSQLWhere += "AND UPPER(p.FORENAME) = '" + strForename + "' "; } if (strSurname.Length != 0) if (intWildS != -1) { strSurname = strSurname.Substring(0, intWildS); strSQLWhere += "AND UPPER(p.SURNAME) LIKE " + UseWildCards(strSurname); } else { strSQLWhere += "AND UPPER(p.SURNAME) = '" + strSurname + "' "; } private string UseWildCards(string pSearchString) { string strRetVal = ""; int intWild1 = -1; int intWild2 = -1; int intWild3 = -1; intWild1 = pSearchString.IndexOf("%",0); intWild2 = pSearchString.IndexOf("%",intWild1+1); intWild3 = pSearchString.IndexOf("%",intWild2+1); //Check for valid wildcard entry if (intWild3 != -1) { MessageBox.Show ("You have specified too many wildcard characters.\n\n" + "Please use one of the following formats: \n\n sa% - sampson, sage\n" + "%son% - sampson, simpson, mason", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { if (intWild2 = -1) { pSearchString = pSearchString.Substring(intWild1, intWild2); strRetVal += "'" + pSearchString + "%' "; } else { pSearchString = pSearchString.Substring(intWild1, intWild2); strRetVal += "'%" + pSearchString + "%' "; } }