Hi,

I'm new using AJAX and I'm developing a page where I need to populate a CheckBoxList based on what the user types (it's like an AutoSuggest). I don't know how to bind the checkboxlist from the database using AJAX.
My code in VB.NET is something like this:

Dim DatabaseConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("MyServer").ConnectionString)
        Dim selectSQL As String = "SELECT Name, Id FROM myTable"
        Dim selectCMD As New SqlCommand(selectSQL, DatabaseConnection)
        selectCMD.Parameters.Add(New SqlParameter("@name", SqlDbType.VarChar))
        selectCMD.Parameters("@name").Value = MyTextBox.Text

        Dim adapter As New SqlDataAdapter
        Dim dTable As New DataTable
        adapter.SelectCommand = selectCMD
        adapter.Fill(dTable)

        MyCheckBoxList.DataSource = dTable
        MyCheckBoxList.DataTextField = "Name"
        MyCheckBoxList.DataValueField = "Id"
        MyCheckBoxList.DataBind()

I think the binding in Ajax would be similar to this, but I don't know. Please, can anyone help me with this?

Thanks a lot!

Ana

Dani AI

Generated

A quick, practical follow-up to what described (UpdatePanel + JS-triggered postbacks): that approach works, but it can be heavy because each keystroke runs much of the ASP.NET page lifecycle. A leaner, more responsive pattern is to expose a small JSON endpoint on the server (a WebMethod, Web API, etc.), call it from JavaScript with a short debounce, and render the checkboxes in the DOM. That keeps network payloads and server work small and makes the UI snappier.

Example server side (VB.NET WebMethod returning a small list of POCOs):

<System.Web.Services.WebMethod()> _
Public Shared Function GetMatches(prefix As String) As List(Of Item)
    Dim result As New List(Of Item)
    Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MyServer").ConnectionString)
        Using cmd As New SqlCommand("SELECT TOP 20 Id, Name FROM myTable WHERE Name LIKE @p + '%'", conn)
            cmd.Parameters.AddWithValue("@p", prefix)
            conn.Open()
            Using rdr As SqlDataReader = cmd.ExecuteReader()
                While rdr.Read()
                    Dim it As New Item()
                    it.Id = Convert.ToInt32(rdr("Id"))
                    it.Name = rdr("Name").ToString()
                    result.Add(it)
                End While
            End Using
        End Using
    End Using
    Return result
End Function

Public Class Item
    Public Property Id As Integer
    Public Property Name As String
End Class

Client-side: debounce input, POST JSON to the WebMethod, then build checkbox elements into a container (use createTextNode so values are safely encoded):

var timer, input = document.getElementById('q'), box = document.getElementById('suggestions');
input.addEventListener('input', function () {
  clearTimeout(timer);
  timer = setTimeout(function () {
    var q = input.value.trim(); if (!q) { box.innerHTML = ''; return; }
    fetch('MyPage.aspx/GetMatches', {
      method: 'POST',
      headers: {'Content-Type': 'application/json; charset=utf-8'},
      body: JSON.stringify({ prefix: q })
    })
    .then(r => r.json())
    .then(j => {
      var items = j.d || j;
      box.innerHTML = '';
      items.forEach(function(it){
        var label = document.createElement('label');
        var cb = document.createElement('input'); cb.type = 'checkbox'; cb.value = it.Id || it.id;
        label.appendChild(cb);
        label.appendChild(document.createTextNode(' ' + (it.Name || it.name)));
        box.appendChild(label);
      });
    }).catch(console.error);
  }, 250);
});

Troubleshooting & tips: always parameterize queries and limit rows (TOP N), debounce keystrokes to avoid DB overload, return compact JSON, and cache frequent queries if possible. If you prefer ready-made widgets, jQuery UI Autocomplete or an ASP.NET control can be used to supply suggestions — but for checkbox lists the client-rendered approach above gives the most control and best performance.

Recommended Answers

All 10 Replies

Mmmm "bind". It's one of those Microsoftish words they use in 101 different ways.

What does it mean here? The VB means just about diddly to me.

Airshow

What I mean for bind is retrieve the values from the Database based on what the user typed and put this values on the CheckBoxList. In other words, the items in the CheckBoxList will be the values retrieved from the Database.
Is there any way to do this using AJAX?

OK, subsidiary question - what is a "CheckBoxList"?

Remember this is the Javascript/DHTML/AJAX forum so we tend to speak standard HTML here.

Airshow

Forget about it! Maybe I don't need to "bind using AJAX" because it's only put my TextBox and CheckBoxList inside an UpdatePanel (using ASP.NET). Sorry about the question (this is that kind of questions beginners ask when don't understand everything very well :)
I think my question would be more like... how to make the CheckBoxList to be populated when the user start typing something in the TextBox? In other words... how to implement the AutoSuggest?

Thanks again,

Ana

Ana,

Sorry, I didn't mean to put you off. I'm sure it's a perfectly reasonable question - just a mater of getting the terminology right for non-VB/ASP folks.

Airshow

No worries. I wrote my previous comment before reading your post, so you didn't put me off.
I think this question is more a ASP.NET/AJAX.NET question =)
But if you have any suggestions of how to implement the AutoSuggest using Ajax/JavaScript in a simple way (I'm beginner in AJAX/Javascript and sometimes it's difficult to understand some codes...), please let me know.
Thanks,

Ana

Ana,

I've used AJAX for several things but not autosuggest. I guess it's fairly trivial given that an appropriate database is available.

Try searching Daniweb for "autosuggest ajax" - there are plenty of results. Maybe one of them will point you in the right direction, though many of the solutions discussed seem to employ PHP server-side rather than ASP. You will probably need to read between the lines.

There are several AJAX tutorials on the web. Google/Altavista will reveal all.

Good luck.

Airshow

Hi Airshow,

Thanks a lot for your replies. Because I'm using ASP.NET what I did was include my textBox and CheckBoxList inside an Update Panel and, using javascript, make a postback happens at every typed letter. And to each letter entered, I called a procedure to bind the CheckBoxList. And now it's working.
But as I said before, this is more an ASP.NET question than a javascript one. Anyways... the fact is that the problem is solved now =)

Thanks again,

Ana

That's brilliant Ana. I'm so pleased for you.

Airshow

how do i add my checkbox list in ajax panel

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.