Monday, August 30, 2010

Auto Complete Extender

Hello Friends,

Now I am going to describe how to use auto complete extender control of ajax control toolkit.

For this I assume that you know the basics of webservice and how to create them.

Step 1. Add Ajax Control Toolkit reference in your website. For this See This Post
Step 2. If the ScriptManager tag is not present is your form then it should be specified inside the Form tag.<asp:ScriptManager Id="sm1" runat="server" />

Step 3. create a webservice in your solution
add this line
[System.Web.Script.Services.ScriptService]

 to your webservice just above the class defination and below the mentioned two lines
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]


Create a Method in webservice which meets your requirments like this one


[WebMethod]
public string[] GetInfo(string prefixText)
{
 int count = 10;
 string sql = "Select * from test Where Name like @prefixText";
 SqlDataAdapter da = new SqlDataAdapter(sql,”Your Connection String Comes Here”));
 da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = prefixText+ "%";
 DataTable dt = new DataTable();
 da.Fill(dt);
 string[] items = new string[dt.Rows.Count];
 int i = 0;
 foreach (DataRow dr in dt.Rows)
 {
  items.SetValue(dr["Name"].ToString(),i);
  i++;
 }
 return items;
}






Step4: Now insert  auto complete extender to your page like this


<cc1:AutoCompleteExtender TargetControlID="txtName" CompletionInterval="1000"
ID="AutoCompleteExtender1" UseContextKey="false" MinimumPrefixLength="1" ServiceMethod="GetInfo"
ServicePath="../AutoComplete.asmx" runat="server">
</cc1:AutoCompleteExtender>


where service path is the path to your webservice and service method is the method name created  for auto complete
and target control id is the id of the text box where you want auto complete.
also set AutoCompleteType property of text box to disabled.


Now all set 
run your solution and enjoy.......