Search code examples
c#asp.netdatatableautocompleteextender

Can I use a DataTable for a AutoCompleteExtender from AjaxToolKit


I built a ASP.NET Webapplication and I have a TextBox where a User can find a other User. For this I want use the AutoCompleteExtender from AjaxToolKit. The Data I get from the Active Directory. If I start my Page the Application create a DataTable with all UserDate from ActiveDirectory and my Question is.

Can I use a DataTabe for the Informations in a AutoCompleteExtender? If I can use this how I can use this ?


Solution

  • According to the official documentation you can't. Not only you can't use a DataTable but you must implement a web service and within it, a webmethod with a very specific signature.

    If you don't mind using jQuery, I can show you an example using jQuery.

    Update:

    Using jQuery all you need to do is include the following libraries in your markup:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js" type="text/javascript"></script>
    

    On your markup, you can add an asp:hiddenElement and the text element that will be used for autocompletion as so:

    <asp:HiddenElement id="hdnAutoComplete" runat="server" />
    <asp:TextBox id="txtAutoComplete" runat="server" />
    

    Now, you just add the following Javascript function:

    $(function(){
    var items = eval($('#<%=hdnAutoComplete.ClientID%>').val());
    
      $( "#<%=txtAutoComplete.ClientID%>" ).autocomplete({
         source: items
       });
    
    });
    

    Finally, you need to set the elements that you are going to use for autocompletion from codebhind. Since you want to use a DataTable, I'll show you an easy way:

    protected void Page_Load(object sender, EventArgs e)
    {
         DataTable t = ...//your datatable is this
    
         var query = (from c in t.AsEnumerable()
                     select c.Field<string>("NameOfTheColumnYouWant")).ToArray();
    
         //this will create a javascript array on the client-side when it's eval'd 
         hdnAutoComplete.Value = "["+string.Join(",",query)+"]";
    
    }
    

    Read more examples from jQuery UI's official documentation here.