Adding an autocomplete textbox using JavaScript



Thanks to jQuery UI, you can use a combination of JavaScript and C# code to set a textbox with an autocomplete filter.



You can download the TEXTBOX_AUTOCOMPLETE process as an example.

How it works

To create the autocomplete filter, we used jQuery UI’s Autocomplete widget.

To get the filtered list content, we execute a SQL query in the code-behind. The results will be formatted in JavaScript array format and set in a hidden field (REQUEST_USER_LIST)

private void GetUser()
    string queryString = "SELECT CONCAT(LASTNAME,' ',FIRSTNAME) as name, USERNAME FROM USERS";
    string queryJs = "[";
    using(System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["MainDbSource"].ToString()))
        System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(queryString, sqlConnection);
            using (System.Data.SqlClient.SqlDataReader reader = command.ExecuteReader())
                if (reader.HasRows)
                    while (reader.Read())
                        queryJs = queryJs + "{ value :'" + reader[0].ToString() +
                            "', login :'" + reader[1].ToString() + "'},";
                queryJs += "]";

    REQUEST_USER_LIST.Text = queryJs;

To add the JavaScript code, go to the Web References tab in the Form configuration panel.


Code example

This example gets the value of the hidden REQUEST_USER_LIST field, and transforms this into a JavaScript array.

if(typeof $selectedObject === "undefined") {
    $(function() {

       var array = eval($("#REQUEST_USER_LIST").val());

            source : array,

             select : function(event, ui){ // When a selection is done
                $('#REQUEST_LOGIN').val(ui.item.login); // we add login in the specific field