Introduction
Begin by adding a using statement for System.text library, since StringBuilder is located in the System.Text namespace. Use StringBuilder to modify a string without creating a new object or concatenating many strings together in a loop.
In this article I will show how to search using Google for a value in a TextBox using ASP.NET.
Complete Program
Search_Value.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
public partial class Search_Value : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string text = string.Empty;
StringBuilder txtaddress = new StringBuilder();
txtaddress.Append("https://www.google.com/search?q=");
if (searchtxt.Text != string.Empty)
{
text=searchtxt.Text.Replace(' ','+');
txtaddress.Append(text+' '+ '+');
}
string url = txtaddress.ToString();
Response.Redirect(url, false);
}
catch (Exception ex)
{
Response.Redirect(ex.ToString());
}
}
}
Search_Value.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Search_Value.aspx.cs" Inherits="Search_Value" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="border-style: double; border-width: medium; padding: inherit; margin: inherit; height: 194px;
width: 349px; background-color: #808080; visibility: visible;">
<br />
<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Italic="True" Font-Size="Large"
ForeColor="Blue" Text="Search a value in Google"></asp:Label>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Enter Search Text"></asp:Label>
<asp:TextBox ID="searchtxt" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Font-Bold="True" OnClick="Button1_Click" Text="Search" />
<br /><br /><br /><br /><br /><br /><br /><br /></div><br />
</form>
</body>
</html>
Output
For more information, download the attached sample application.