Wednesday, January 6, 2010

Auto Suggest Textbox in Asp.net with Auto Complete Extender

To use auto suggest text box first we need to download Ajax Toolkit.
To create auto suggest text we need to write a web service.

step 1 )

Write a web service as follows


[WebMethod]
public string[] GetCountryInfo(string prefixText)
{

 int count = 10; 
 string sql = "Select * from Country Where Country_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["Country_Name"].ToString(),i); 
  i++; 
 } 
 return items; 
}



and dont forget to add

[System.Web.Script.Services.ScriptService]


step 2 )
 set the AutoCompleteExtender’s TargetControlID property to the TextBox Id. 

Set ServicePath as WebService.asmx, ServiceMethod as GetCountryInfo and MinimimPrefixLength as 1.

 if u want search multiple values then use delimiter property in Autocompleteextender

and also set ShowOnlyCurrentWordInCompletionListItem =true

 then it only show current search values only.
in Ajax Toolkit 2.0 we don't have ShowOnlyCurrentWordInCompletionListItem. 

All the best 

No comments:

Post a Comment