If I was doing this then I'd have some code like this:
protected void Search_Click(object sender, EventArgs e)
{
var constr = ConfigurationManager.ConnectionStrings["ConnectToDB"].ConnectionString;
var sql = new StringBuilder();
sql.Append("Select [ITEM No#], [Company Name], [Discipline Required], [Service Description], Institution, [Award Date]");
sql.Append(" from PSP_Report ");
using (var con = new SqlConnection(constr))
{
using (var xp = new SqlCommand())
{
xp.Connection = con;
var andRequired = false;
var whereAdded = false;
AddASearchItem(ref whereAdded, ref andRequired, sql, Search1.Text, "[ITEM NO#]", 1, xp);
AddASearchItem(ref whereAdded, ref andRequired, sql, Search2.Text, "[Company Name]", 2, xp);
AddASearchItem(ref whereAdded, ref andRequired, sql, Search3.Text, "[Discipline Required]", 3, xp);
xp.CommandText = sql.ToString();
con.Open();
var da = new SqlDataAdapter {SelectCommand = xp};
var ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
con.Close();
}
}
}
protected void AddASearchItem(ref bool whereAdded, ref bool andRequired, StringBuilder s,
string searchText, string colName, int item, SqlCommand cmd)
{
if (string.IsNullOrEmpty(searchText)) return;
if (!whereAdded)
{
s.Append(" where ");
whereAdded = true;
}
else
if (andRequired) s.Append(" AND");
s.Append(string.Format(" {0} LIKE @search{1}", colName,item));
cmd.Parameters.AddWithValue("@search" + item.ToString(), "%" + searchText + "%");
andRequired = true;
}
Points to note:
1 - I've used a StringBuilder to dynamically build up the sql command text. This is better than concatenating strings (because strings are immutable)
2 - I have a little function that only adds search items onto the SQL if the relevent search textbox has something in it.
3 - I need to work out if the words " WHERE " or " AND " need to be added to the SQL.
4 - If none of the search boxes have anything in them then all records will be returned