Tuesday, September 17, 2013

Display No Data Found with AJAX AutoComplete Extender

Hi all,
try this example to Display No Data Found Message with AJAX AutoComplete Extender
1) Open VS 2008 and create new web site
2) Add new web page and from Toolbox drag and drop ScriptManager , TextBox and AJAX AutoComplete Controls

Aspx Page

<head runat="server">
 <title></title>
 <style type="text/css">
 body
 {
 font-family: Arial;
 font-size: 10pt;
 }
 .autocomplete_completionListElement
 {
 margin: 0px !important;
 background-color: white;
 color: windowtext;
 border: buttonshadow;
 border-width: 1px;
 border-style: solid;
 cursor: 'default';
 overflow: auto;
 max-height: 200px;
 text-align: left;
 list-style-type: none;
 padding: 0px;
 }
 </style>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
 </asp:ScriptManager>
 <asp:TextBox ID="txtContactsSearch" runat="server"></asp:TextBox>
 <cc1:AutoCompleteExtender ServiceMethod="SearchCustomers" MinimumPrefixLength="2"
 CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" TargetControlID="txtContactsSearch"
 ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false" CompletionListCssClass="autocomplete_completionListElement"
 OnClientItemSelected="OnClientItemSelected">
 </cc1:AutoCompleteExtender>
 <script type="text/javascript">
 function OnClientItemSelected(sender, args) {
 var value = args.get_value();
 if (value == "No data found.") {
 $get("<%=txtContactsSearch.ClientID %>").value = "";
 }
 }
 </script>
 </div>
 </form>
</body>
</html>


Code Behind


[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchCustomers(string prefixText, int count)
{
 using (SqlConnection conn = new SqlConnection())
 {
 conn.ConnectionString = ConfigurationManager
 .ConnectionStrings["constr"].ConnectionString;
 using (SqlCommand cmd = new SqlCommand())
 {
 cmd.CommandText = "select ContactName from Customers where " +
 "ContactName like @SearchText + '%'";
 cmd.Parameters.AddWithValue("@SearchText", prefixText);
 cmd.Connection = conn;
 conn.Open();
 List<string> customers = new List<string>();
 using (SqlDataReader sdr = cmd.ExecuteReader())
 {
 while (sdr.Read())
 {
 customers.Add(sdr["ContactName"].ToString());
 }
 }
 conn.Close();
 if (customers.Count == 0)
 {
 customers.Add("No data found.");
 }
 return customers;
 }
 }
}




No comments:

Post a Comment