Text Search with the help of ASP.NET


I create a simple search textbox in asp.net with the help of LIKE operator (SQL)

Step 1: First we create a table in database:->

create table textsearch
(
id int identity( 1,1),
fname varchar(50),
lname varchar(50)

)

I create a simple search textbox in asp.net with the help of LIKE operator (SQL)

Step 2: In aspx page,I use the following controls:

a) TextBox (txtsearch) :- For Search the Text (Set :- AutoPostBack="True" EnableViewState="False")
b) ListBox (lstsearch):- To populate the search list (Set :- AutoPostBack="True" EnableViewState="True")
c) Button (btnsearch):- To search the Text
d) Label(lblsearch) :- To show the search text

Step 3: In the .cs page:

protected void Page_Load(object sender, EventArgs e)
{
lstsearch.Visible = false;
}
protected void txtsearch_TextChanged(object sender, EventArgs e)
{
lstsearch.Visible = false;
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
conn1.Open();
SqlCommand cmd1 = new SqlCommand("select * from textsearch where fname like '%" + txtsearch.Text + "%'", conn1);
SqlDataReader dr1;
dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
lstsearch.Items.Add(dr1["fname"].ToString());
lstsearch.Visible = true;
}
dr1.Close();
conn1.Close();
}
protected void lstsearch_SelectedIndexChanged(object sender, EventArgs e)
{
txtsearch.Text = lstsearch.SelectedItem.Text;
lstsearch.Visible = false;
lstsearch.Items.Clear();
}
protected void btnsearch_Click(object sender, EventArgs e)
{
lblsearch.Text = txtsearch.Text;
lstsearch.Visible = false;
}