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.