This article explains to fill a AutoComplete Textbox from the data fetched from database.
Description:
Everyone knows about the AutoComplete Textbox. It is an ASP.NET AJAX extender that can be attached to any TextBox control. When the user types some letters in the Textbox, a popup panel will come to action and displayed the related words. So that the user can choose exact word from the popup panel. Here I tried to explain how this AutoComplete fetches data from the database through a Webservice.
Open Microsoft Visual Studio, click on New Website. Then choose ASP.NET Ajax Enabled Website and change the location to point your http://localhost/AutoComplete folder. Obviously, Default.aspx is added to your solution explorer.
Now drag and drop a Textbox from your Toolbox. Then drag and drop a ScriptManager and AutoCompleteExtender to your Default.aspx page. Then add a webservice to your project as WebService.asmx. First thing you have to do is to add the ScriptService reference to the webserive as follows.
System.Web.Script.Services.ScriptService
[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;
}
The above webmethod takes prefixText as argument, sends it to the query to fetch only the related words that starts with the prefixText values. Then it returns the result as an array of strings.
Now, it's time to run the project. Select the Default.aspx and click on View in Browser. You can see the excellent application starts to run. Type your country's first letter. See all the countries starts with that letter will appear in the popup.