Click here to Skip to main content
11,410,536 members (56,174 online)
Click here to Skip to main content

Using Google Co-op's Custom Search Engine

, 19 Dec 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
This article shows how easy it is to use ASP.NET and Google Co-op's Custom Search Engine to build your own search engine.

Sample Image - CustomSearchEngine.jpg


This article shows how easy it is to create your own custom search engine using ASP.NET and Google Co-op’s Custom Search Engine feature. 

Creating Your Search Engine

The very first step you must take is to visit (Note that you must have a Google Account. If you don’t have one, ask around. GMail invites are a dime a dozen these days.) Once there, follow the instructions to create your custom search engine.

For this article, I used the following settings:

Sites to Search

Sites to search:
How to search these sites: Search only these sites.

Collaborate with others

Who can collaborate: Only people I invite may contribute to this search engine.

Where to Host the Custom Search Engine

You have two options on how you can display your search engine to users: Google can host it for you, or you can host the search box and results on your site. For this article, I opted for the latter.

To configure this option:

  1. Return to the Google Co-op Custom Search Engine site’s home page (
  2. Click on the My Search Engines link.
  3. When the list of your custom search engines shows up, click on the link that says “Control Panel”.
  4. Next, click on the link that says “Code”.
  5. Select the radio button next to the option that says “Host a search box and search results on your own site…”.
  6. Also, specify the URL of the page on your site where you want the search results to appear.
  7. Finally, after you select the location where you want to display the AdSense ads in your search results, click the Save Changes button.

Search Box Code and Search Results Code

On that same “Code” page in your custom search engine control panel, you will see two multi-line text boxes containing JavaScript code. The first contains a small form that contains your search box, the second is pure JavaScript that aids in the rendering of your search results.

Using the Google-generated Search Box Code Outside of the Server-side FORM Tag

You can use the search box code generated by Google, provided you place it outside of your web form’s server-side FORM tag. I tested this locally, and it worked beautifully. However, I’m sure I’m not alone in wanting the ability to put the search box somewhere inside the server-side FORM tag and still have my custom search engine operate correctly.

Using ASP.NET Server Controls and HtmlControls to Emulate Google's Search Box Inside the Server-side FORM Tag

I solved this problem by using ASP.NET server controls and HtmlControls to emulate the behavior of Google’s search box form, while still providing the server-side capabilities that we all know and love.

You’ll need to reference the search box JavaScript/HTML code from the Custom Search Engine control panel. I simply included it in my ASPX page in an HTML comment. This is what it looks like:

<!-- Google CSE Search Box Begins -->
<form id="searchbox_014373149466545347614:dygl7dqicp4" action="Default.aspx">
  <input type="hidden" name="cx" value="014373149466545347614:dygl7dqicp4" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
  <input type="hidden" name="cof" value="FORID:9" />
<script type="text/javascript" 
<!-- Google CSE Search Box Ends -->

You’ll need four ASP.NET controls to mimic the functionality of this form:

  • A HiddenField control to mimic cx
  • A TextBox control to mimic q
  • Another HiddenField control to mimic cof
  • A Button control to mimic sa

I also added a RequiredFieldValidator to prevent postbacks from happening when the user tries to submit the search query with an empty TextBox.

Here are the control declarations from the ASPX file:

<asp:TextBox ID="q" MaxLength="512" Width="275px" AutoPostBack="false" runat="server" />
<asp:Button ID="_btnSearch" Text="Google Search" 
     OnClick="_btnSearch_Click" runat="server" />
<asp:RequiredFieldValidator ID="_rfvQ" ControlToValidate="q" runat="server" />

<asp:HiddenField ID="cx" Value="014373149466545347614:dygl7dqicp4" runat="server" />
<asp:HiddenField ID="cof" Value="FORID:9" runat="server" />

The “dummyHidden” Input Control

You’ll notice in the ASPX page that there is a plain HTML input control called dummyHidden that is never visible to the user. This is necessary in order to force the search button’s Click event to fire on the server side when the search text box has focus and the user hits the Enter key. This only works when there are two or more text boxes in the form. Based on my research, this appears to be an Internet Explorer-specific problem, and it was the only available workaround I could find. If you have a better solution, please let me know.

Finally, you’ll need to copy the SCRIPT include and place it somewhere in your ASPX page.

The Search Results

For this article, the search results are displayed on the same page as the search box. No ASP.NET emulation is necessary here. Simply copy the JavaScript code and paste it into your ASPX file where you want the search results to appear. Here is what it looks like in my ASPX file:

<!-- Google Search Result Snippet Begins -->
<div id="results_014373149466545347614:dygl7dqicp4"></div>
<script type="text/javascript">
  var googleSearchIframeName = "results_014373149466545347614:dygl7dqicp4";
  var googleSearchFormName = "searchbox_014373149466545347614:dygl7dqicp4";
  var googleSearchFrameWidth = 600;
  var googleSearchFrameborder = 0;
  var googleSearchDomain = "";
  var googleSearchPath = "/cse";
<script type="text/javascript" 
<!-- Google Search Result Snippet Ends -->

Code-behind: Button.Click

This is where the magic happens. Mercifully, Google uses the GET method to send form data, so we merely need to append our search parameters to the query string and redirect the user to the search results page. For this article, that means simply redirecting the user back to the same page, though the results could easily be displayed on a separate physical page.

The search query from the q TextBox and the HiddenField values are all needed in the query string. See the code below:

protected void _btnSearch_Click (Object sender, EventArgs e)
    if (!IsValid)

    Response.Redirect (
            HttpUtility.UrlEncode (SanitizeUserInput (q.Text.Trim ())),
            HttpUtility.UrlEncode (cx.Value),
            HttpUtility.UrlEncode (cof.Value)

    Context.ApplicationInstance.CompleteRequest ();

Important: Be sure to take the time to sanitize and URL-encode the user’s input. I have provided a basic function for doing so, but it is your responsibility to ensure that your applications are safe.

Code-behind: Page.Load

The last bit of code is in the page’s Load event handler. All it does is look for the querystring parameter q, and if it exists, it puts that value in the TextBox q so that the user can see the term for which they last searched. Note that this only happens when the request is not a postback. Because of the redirect, we can’t use ViewState to keep track of the last search term.

Again: Remember to sanitize all user input. Your application’s safety is your responsibility!

protected void Page_Load (Object sender, EventArgs e)
    if (!IsPostBack)
        String query = Request.QueryString["q"];
        if (!String.IsNullOrEmpty (query))
            q.Text = SanitizeUserInput (HttpUtility.UrlDecode (query.Trim ()));


Well, there you have it. With one simple ASP.NET form, we have created a custom search engine that searches only pages on The Code Project. Google Co-op has done an extraordinary job in making this such a simple task for us end users.


  • 2006-10-27: Initial release.
  • 2013-12-19: Removed the link to the live demo. 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jon Sagara
Software Developer (Senior) Sagara Software, Inc.
United States United States
Jon graduated from Cal Poly with a B.S. Computer Engineering. He is currently building a Silverlight-based report scheduling interface for a pharmaceutical reporting company.

When he's not fooling around with computers or reading, he's busy spending time with his super wife, Kelly, his two boys, and their rambunctious dog, Homer.

Visit my blog
Follow on   Twitter

Comments and Discussions

QuestionCould we apply it to MVC? PinmemberMohammad A. Amer26-Jun-14 1:08 
Questionerror PinmemberMember 1063450228-Feb-14 21:23 
Questioncustomize output Pinmemberdafuq6-Jan-12 2:27 
AnswerRe: customize output PinmemberJon Sagara9-Jan-12 8:31 
QuestionThanks PinmemberXmen W.K.19-Jun-11 10:04 
GeneralSearch Results on a Different Page? PinmemberChristopher Irwin7-Jun-11 9:06 
GeneralRe: Search Results on a Different Page? PinmemberJon Sagara9-Jun-11 8:33 
GeneralRe: Search Results on a Different Page? PinmemberChristopher Irwin9-Jun-11 9:04 
GeneralIsValid is not declared Pinmembervipernet027-Nov-10 16:28 
GeneralWidth of iframe too large Pinmemberanemiccolo1-Feb-10 11:05 
GeneralRe: Width of iframe too large PinmemberJon Sagara1-Feb-10 11:37 
GeneralForms authentication and Google Custom Search PinmemberGeorg Kakasevski14-Jan-10 8:41 
GeneralThanks! Pinmembervegeta4ss10-Nov-09 6:09 
GeneralSame as CodeProject CSE PinmemberAnand@DotNet28-Jun-09 22:50 
GeneralWill target to our site only... PinmemberAnand@DotNet28-Jun-09 21:26 
GeneralSearch page refreshing twice Pinmembermatharuajay20-May-09 4:15 
GeneralRe: Search page refreshing twice PinmemberJon Sagara20-May-09 6:45 
GeneralRe: Search page refreshing twice Pinmembermatharuajay24-May-09 21:04 
GeneralSearch result opening again and again. PinmemberMember 314438510-Feb-09 4:08 
QuestionHow to get the Google watermark? PinmemberDavid Moody14-Jan-09 6:20 
AnswerRe: How to get the Google watermark? Pinmemberytzipp26-Feb-09 3:48 
GeneralRe: How to get the Google watermark? Pinmemberboydd_uk17-Mar-09 0:49 
QuestionI have one question Pinmemberintsafi28-Oct-08 8:25 
QuestionHow it will be in PinmemberKubulos9-Aug-08 1:20 
AnswerRe: How it will be in PinmemberNika Asgari7-Sep-08 3:06 
GeneralThanks Pinmembersnashter26-Jan-08 6:59 
GeneralAnother way of doing it is Javascript PinmemberYanDav24-Jan-08 22:31 
GeneralKeep redirecting to result page after click Back button Pinmemberkunthea17-Jan-08 0:30 
GeneralThanks! Pinmemberabidur9-Jan-08 7:48 
Questioncan we modify code? Pinmemberpravin parmar29-Nov-07 0:11 
GeneralThank You! PinmemberFlashSand4-Oct-07 11:24 
GeneralSearch works only for first time only PinmemberAamir Bashir12-Sep-07 21:55 
GeneralProblem with code PinmemberThe Apocalypse8-Aug-07 0:58 
GeneralRe: Problem with code PinmemberJerode27-Sep-07 11:22 
GeneralExport Result to Excel file PinmemberOrtiga23-Jul-07 7:03 
GeneralNo results are shown PinmemberDEGT27-Jun-07 0:36 
GeneralRequest Validation PinmemberDEGT26-Jun-07 23:51 
GeneralSearch box disables other buttons on same page PinmemberKennyGZ25-Jun-07 12:32 
AnswerRe: Search box disables other buttons on same page PinmemberKennyGZ26-Jun-07 9:42 
Generalsearch results page url Pinmemberpathless1-Jun-07 17:40 
QuestionPassword Protected Sites Pinmemberkengineer17-May-07 7:48 
QuestionWhat if the search box is in a usercontrol? Pinmemberorengold5-Mar-07 18:13 
GeneralMasterpage problem [modified] Pinmemberkemall28-Feb-07 5:12 
GeneralRe: Masterpage problem PinmemberJon Sagara28-Feb-07 5:40 
GeneralRe: Masterpage problem Pinmemberkemall28-Feb-07 6:49 
GeneralRe: Masterpage problem PinmemberJon Sagara28-Feb-07 8:01 
QuestionResult page reloads twice Pinmemberjes m george20-Feb-07 0:34 
AnswerRe: Result page reloads twice Pinmemberorengold5-Mar-07 18:03 
GeneralRe: Result page reloads twice PinmemberBordi7-May-07 8:26 
Questionsearch box in the master page? Pinmembers. o.18-Jan-07 10:43 
I'm using a master page on my website and as I'd like there to be a search box on every page, it seems logical to put code there. So I've added your code to the master and master.cs pages, and it's not quite working. I get a bunch of build errors like "The name 'q' does not exist in the current context" (same for the other variables; cx, cof, and IsValid). It worked great when I tried putting it in a regular .aspx page. Am I asking too much? Any suggestions?


General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150414.5 | Last Updated 19 Dec 2013
Article Copyright 2006 by Jon Sagara
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid