Monday, 14 October 2013

Google Like Search Box with Suggestion

Here are some tips to generate Google Like Search box with Suggestions.

Step 1: Create a page which will be called on TextChange event of theSearch Text Box and write the code as follows:

using System.Data.SqlClient;
using System.Text; 


string clientName;
    protected void Page_Load(object sender, EventArgs e)
    {
      clientName = Request["search"].ToString();
      Getresult();
       
    }


private void Getresult()
    {
        DataTable dt = new DataTable();      
         SqlConnection con = new SqlConnection();
         con.ConnectionString = "data source=yourServer;initial catalog=yourdatabaseIntegrated security=true;";        
        SqlCommand cmd=new SqlCommand();
        cmd.Connection=con;
        cmd.CommandText = "select studName from tbl_stud1 where studName like @nm";
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@nm", clientName + "%");
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        StringBuilder sb = new StringBuilder();
      
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append(dt.Rows[i].ItemArray[0].ToString()  + "~");   //Create Con
            }
        }
           Response.Write(sb.ToString());  
    }


Step 2: Now create the markup of main search page as follows:

<script language="JavaScript" type="text/javascript" src="SearchSuggest.js"></script>
    <style type="text/css" media="screen">   
       body
       {
        font: 11px arial;
       }
       .suggest_link
       {
       background-color: #FFFFFF;
       padding: 2px 6px 2px 6px;
       }   
       .suggest_link_over
       {
       background-color: #3366CC;
       padding: 2px 6px 2px 6px;   

       color: #FFFFFF;
       }   
       #search_suggest
       {
       position: absolute;
       background-color: #FFFFFF;
       text-align: left;
       border: 1px solid #000000;           
       }
    </style>


<table>
    <tr>
    <td style="font: 20px arial" >
    Welcome to Demo of Google like Search Suggest Text Box
    </td>
    </tr>
    </table>
   
   <input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria"       onkeyup="searchSuggest(event);" autocomplete="off" style="width: 544px" />&nbsp;
    <div id="search_suggest" style="z-index: 2; visibility: hidden;position: absolute;left: 11px; width: 548px; top: 70px"></div>
    <input type="submit" id="cmdSearch" name="cmdSearch" value="Search" alt="Run
Search" />






Output:




   

No comments:

Post a Comment