Home / ASP.NET Wiki / HTML / Web Controls / TextBox / Simple search TextBox in asp.net

Simple search TextBox in asp.net

 Rate It (0)

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)

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 testseach 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;

    } 

 

Revision number 1, Monday, August 09, 2010 5:15:45 PM by miya2008
This is not the most up to date version of this article. The most recent version can be found here.

Comments

Good effort. Moreover u can also search last name at the same time to get better search results: select * from testseach where fname+lname like '%" + txtsearch.Text + "%'"

do keep in mind that you should never directly concatenate the contents of a textbox into your sql statements like that as it opens you up to sql injection attacks. all user input values need to be parameterized. refer: http://forums.asp.net/t/1568268.aspx

excellent article :) :) but usage of SP would've been more better

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. abiruban (1)