I have added a bool switch to take care of that....
compacted the code
static void Main()
{
var S1 = new System.Web.UI.WebControls.TextBox();
var S2 = new System.Web.UI.WebControls.TextBox();
var S3 = new System.Web.UI.WebControls.TextBox();
var S4 = new System.Web.UI.WebControls.TextBox();
S1.Text = "abcd";
S2.Text = "abcd";
S3.Text = "abcd";
S4.Text = "abcd";
bool isSetAnd = false;
var sqlcmd = new SqlCommand();
StringBuilder sb = new StringBuilder();
sb.Append("Select * from Cases WHERE ");
generateQueryText(S1.Text, "S1", ref sb, ref isSetAnd, ref sqlcmd);
generateQueryText(S2.Text, "S2", ref sb, ref isSetAnd, ref sqlcmd);
generateQueryText(S3.Text, "S3", ref sb, ref isSetAnd, ref sqlcmd);
generateQueryText(S4.Text, "S4", ref sb, ref isSetAnd, ref sqlcmd);
Console.WriteLine(sb.ToString());
sqlcmd.CommandText = sb.ToString();
sqlcmd.CommandType = CommandType.Text;
}
private static void generateQueryText(string textBoxText, string textBoxID, ref StringBuilder sb, ref bool isSetAnd, ref SqlCommand sqlcmd)
{
if (textBoxText != string.Empty)
{
if (isSetAnd)
{
sb.Append(" AND ");
}
isSetAnd = true;
sb.Append("CaseRegYear LIKE @" + textBoxID);
sqlcmd.Parameters.AddWithValue("@" + textBoxID, "%" + textBoxText + "%");
}
}