Wednesday, 20 February 2013

Text-box Auto-completion in c#.net using Ajax.


Have you encountered or wondered how to get the effect you get while searching for a profile on the Facebook page on the Search Tab or how to get the Google auto-completion of characters and sentences with a long list of options to choose from? 

Here is one of the ways you can achieve it in ASP.net and AJAX. This code uses .Net framework and c# along with the ever cool AJAX functionality to achieve the same in a few lines of code. Follow the steps below to get the similar effect for people trying to achieve the above.



  • Drag and drop Auto-complete extender on page.
  • Write Text-box id as target id in auto-complete extender.


Here is an example:

In .aspx page write following code:


<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc2:AutoCompleteExtender ID="TextBox2_AutoCompleteExtender" runat="server"
DelimiterCharacters="" Enabled="True" ServiceMethod="GetCompletionList"
CompletionListCssClass="autocomplete" TargetControlID="TextBox1" UseContextKey="True"
MinimumPrefixLength="1">

In .cs page write the below code

public static string[] GetCompletionList(string prefixText, int count, string
contextKey)
{

MySqlConnection cn = new MySqlConnection("server=localhost; database=demo;
user id=root; password=");

DataSet ds = new DataSet();
DataTable dt = new DataTable();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
//Query
cmd.CommandText = "select name from table where name like @myParameter";
cmd.Parameters.AddWithValue("@myParameter", prefixText + "%");

try
{

cn.Open();
cmd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);

}
catch
{
}
finally
{
cn.Close();
}
if (ds != null)
{
dt = ds.Tables[0];
}

//Then return List of string(txtItems) as result
List<string> txtItems = new List<string>();
String dbValues;

foreach (DataRow row in dt.Rows)

{

//String From DataBase(dbValues)
dbValues = row["name"].ToString();
txtItems.Add(dbValues);

}

return txtItems.ToArray();

}

Its as simple as that!


No comments:

Post a Comment