Tuesday, July 17, 2012

c# - Search functionality on a database table using Dynamic SQL

I have seen this request on forums and this is one of the most common type of searches that I come across in applications.

Search a table for a given string and retrieve matching records.
use case:Retrieve parts from a PartsInventoryTable which matches a certain name.

The page would have a textbox for search string,dropdownlist with columns from the database tables, a button to retrieve the search records that match the search string and a gridview to display the search records.

Below is the code for this simple database table search.


public void GetSearchResults() 
        { 
            string searchString = MyTextBox.Text.Trim(); 
            string searchParam = MyDropDownList.SelectedValue; 
  
            StringBuilder searchQuery = new StringBuilder("SELECT * FROM MYTABLENAME WHERE "); 
            searchQuery.Append(searchParam); 
            searchQuery.Append(" LIKE "); 
            searchQuery.Append(" %"); 
            searchQuery.Append(searchString); 
            searchQuery.Append("% "); 
 
            SqlConnection conn = new SqlConnection(connectionString);            
 
            SqlCommand cmd = new SqlCommand(searchQuery.ToString(),conn); 
            cmd.CommandType = CommandType.Text; 
 
 
            conn.Open(); 
            try 
            { 
                dataReader = cmd.ExecuteReader(); 
 
            } 
            catch (Exception ex) 
            { 
                //ExceptionHandler 
            } 
            finally 
            { 
                conn.Close(); 
            } 
            if (dataReader != null) 
            { 
                MyGridView.DataSource = dataReader; 
                MyGridView.DataBind(); 
            } 
        }

1 comment:

Anonymous said...

The information were very helpful for me, I've bookmarked this post, Please share more information about this
Thanks