Pages

Monday, August 19, 2013

How to use Google Search in Asp.net

This article will be explaining how to use Google search for search value from the Textbox in Asp.net. In this example we are using 'System.Text' namespace.

Step 1
In 'Default.aspx' page add following control.

<form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Enter value" style="top: 251px; left: 374px; position: absolute; height: 19px; width: 77px"></asp:Label>
        <asp:TextBox ID="searchText" runat="server" style="top: 244px; left: 460px; position: absolute; height: 22px; width: 169px"></asp:TextBox>
        <asp:Button ID="searchBtn" runat="server" Text="Search" style="top: 243px; left: 645px; position: absolute; height: 26px; width: 56px" OnClick="searchBtn_Click" />
    </div>
</form>

Step 2
In 'Default.aspx.cs' page write following code on button click.

protected void searchBtn_Click(object sender, EventArgs e)
    {
        try
        {
            string strTxt = string.Empty;
            StringBuilder strBuild = new StringBuilder();
            strBuild.Append("https://www.google.com/search?q=");
            if (searchText.Text != string.Empty)
            {
                strTxt = searchText.Text.Replace(' ', '+');
                strBuild.Append(strTxt + ' ' + '+');
            }
            string url = strBuild.ToString();
            Response.Redirect(url, false);
        }
        catch (Exception ex)
        {
            Response.Redirect(ex.ToString());
        }
    }

Step 3

Finally run project enter value in textbox and click on 'Search'.

No comments:

Post a Comment