Thursday, October 29, 2009

Create Autocomplete TextBox using AJAX in Asp.net 3.5




Please visit my new Web Site WWW.Codedisplay.com



Asp.net 3.5 ease our life. As you knew that Microsoft community published a series of controls named ASP.NET AJAX Control Toolkt. Which you can download from http://www.asp.net/ajax . The AutoCompleteExtender is one of them. You can use this AutoCompleteExtender in your page to make an autocomplete textbox within just few minutes. You can't imagine how much its easy. In this AJAX tutorial i will show you how one can create Autocomplete TextBox using AJAX in ASP.NET 3.5. The Autocomplete TextBox provides user a nice & cool experience while entering data. Let in your page one of the TextBox is used to enter referrer name. You knew that to the referrer name is a tedious job for yur application user. So you can incorporate autocomplete facilty to give your user best UI experience.

Desired Output:


To make an Autocomplete Textbox first create a project. Then opne the default.aspx page in design view. Add ScriptManager , TextBox , Autocomplete Extender from toolbox. Now your HTML markup will be:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
<title>Ajax Autocomplete Extender Tutorial</title>
</head>

<body>
<form id="form1" runat="server">
<div>

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

<asp:Label runat="server" ID="lblReferrerName" Text="Referrer: "></asp:Label>

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

<cc1:AutoCompleteExtender
ID="AutoCompleteExtender1" runat="server" TargetControlID="txtName"
MinimumPrefixLength="2" CompletionInterval="10" EnableCaching="true" CompletionSetCount="3"
UseContextKey="True" ServiceMethod="GetCompletionList">
</cc1:AutoCompleteExtender>

</div>
</form>
</body>
</html>

Don't confuse for ServiceMethod="GetCompletionList" line from the above code. I will show you how you can create webservice method for Autocomplete Extender. Move your mouse on the TextBox. Then from TextBox control smart tag, select the Add AutoComplete page method option from the provided menu, shown in below:


After that you will found that a webservice method will be added in your default.aspx.cs page named GetCompletionList. Now you need to modify this method to return your expected set of data. Now look at my code from below.

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
string connectionString = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
// Try to use parameterized inline query/sp to protect sql injection
SqlCommand cmd = new SqlCommand("SELECT TOP "+count+" Name FROM tblAgent WHERE Name LIKE '"+prefixText+"%'", conn);
SqlDataReader oReader;
conn.Open();
List CompletionSet = new List();
oReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (oReader.Read())
CompletionSet.Add(oReader["Name"].ToString());
return CompletionSet.ToArray();
}
}

Don't forget to add the namespace using System.Collections.Generic;

Code Explanation:
If you observe the web method GetCompletionList you will found three parameters named
prefixText, count, contextKey. Which you can use to enhance your method. Here i have used first two parameters. The prefixText parameter will give you the text that user enter into the textbox. So you can use prefixText parameter in your sql as LIKE clause to match data. The second one count which is used to return no of data. If you specify CompletionSetCount="3" then you will get maximum 3 data. So set the count as per client requirement.

Hope everything is clear now. ANd now you can create AJAX AutoComplete TextBox in your project smoothly.

12 comments:

Anonymous said...

I got an error when I used same code..
error like---
Using the generic type 'System.Collections.Generic.List' requires '1' type arguments

Anonymous said...

Here's a thought, try debugging your code to see if it works before writing a how to on it

Shawpnendu said...

Please add all namespaces that i have describe above. The code is fully working. I didn't get any problem yet. Anyway thanks for sharing.

rajnipankar said...

List< string > CompletionSet = new List< string >();

Anonymous said...

It's not working and when I try to debugging, a popup message window appears stating "There is no source code for the current location "

Tulasi_rams said...

Thanks Alot

Anonymous said...

i am getting error in webusercontrol when am using this .. error was like this
" "Cannot create page method 'GetCompletionList' because no CodeBehind or CodeFile was found."
plz help me

Anonymous said...

its very nice super

Anonymous said...

Thanks... Its is very useful....Thanks Again...

Vardhan Netha said...

i am getting list but how to display that string[] into webform.
Please Help me guys.
Mail: vardhan.nextclick@gmail.com

Unknown said...

Thanks

Anonymous said...

Thanks alot, it helped me :)

vijay

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash