Popular Posts

There was an error in this gadget

Nov 17, 2013

Auto Complete TextBox in asp.net



In .aspx file add these line to head section:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "NewEmployee.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtEmail').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
}
});
}

</script>

In page body:

<input type="text" id="txtEmail" class="autosuggest" />


In .cs file Add these lines:

[WebMethod]
    public static List<string> GetAutoCompleteData(string username)
    {
        string strCon = ConfigurationManager.ConnectionStrings["IRTConnectionString"].ConnectionString;
        List<string> result = new List<string>();
        using (SqlConnection con = new SqlConnection(strCon))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT username FROM t_Employee WHERE username LIKE '%'+@SearchText+'%'", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@SearchText", username);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(dr["username"].ToString());
                }
                return result;
            }
        }
    }


You need to add this reference 'System.Web.Services'.





No comments:

Post a Comment