sd_dracula
sd_dracula

Reputation: 3896

asp.net ListBox update

I have a ListBox with a set of values and I would like to get it updated if data gets added/deleted to it.

The following works but is there a way to not having to call that everytime you modify the contents?

lbUsers.DataSource = myDataSource;
lbUsers.DataBind();

Upvotes: 4

Views: 5590

Answers (3)

David East
David East

Reputation: 32624

I would like to get it updated if data gets added/deleted to it

This all depends on your form UI.

Is point of the page to add Users and display them as they get added? Or is the directive of the page to display all of the currently available users up to the second?

If your objective is the former then you would just rebind the lbUsers ListBox everytime a user is added.

Here is an example of the first situation below:

Add User and Display

Markup

<asp:TextBox ID="txtUsername" runat="server" />
<asp:Button ID="btAdd" runat="server" value="Add" onclick="btAdd_Click" />
<asp:ListBox ID="lbUsers" runat="sever" />

Code-behind

public void AddUser()
{
    string username = txtUsername.Text;

    // Either update the database with a new user
    User newUser = User(username);
    WhateverDataAccessYoureUsing.Add(User);
    List<User> users = WhateverDataAccessYoureUsing.GetAllUsers();
    lbUsers.DataSource = users;
    lbUsers.DataBind();

    // OTHER OPTION
    //
    // Or if no database directly bind the user to the ListBox
    ListItem li = new ListItem(username);
    lbUsers.Items.Add(li);
}

protected void btAdd_Click(object sender, EventArgs e)
{
     AddUser();
}

However, if the page is simply a display the all the users and display the new ones as they are created elsewhere, then you need a combination of AJAX and Server-Side code here. Instead of using a server control, we will use an HTML select because Server Controls cannot be accessed in WebMethods. Also, we will use jQuery to do the AJAX calls.

Displaying Users via AJAX calls

Mark up

<select id="lbUsers" size="4" multiple="multiple">
</select>

<script>
    // When the page is ready to be manipulated
    $(function() {

      // Call the server every three seconds to get an updated list of users
      setInterval(function() {

           $.ajax({ 
                type: "POST",
                url: "Default.aspx/GetUsers",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                   // If we are successful, append the results to lbUser
                   $(result.d).appendTo('#lbUser').hide().fadeIn(500);
                },
                error: function () {
                    // If we encounter an error, alert the user
                    alert("There was a problem getting the new users");
                }
            });

       },3000); // 3000 is 3000 milliseconds which is 3 seconds
    });
</script>

Code-behind

// This annotation is required for all methods that can be accessed via AJAX calls
[System.Web.Services.WebMethod]
public static void GetUsers()
{
   List<User> users = WhateverDataAccessYoureUsing.GetAllUsers();

   string listItems = string.Empty;

   // Loop through the list of users and create the option
   // that will be displayed inside of lbUsers
   foreach (User u in users)
   {
       listItems += CreateOption(u.Username);
   }

   // return the string value that will be appended on to lbUsers
   return listItems;
}

// This creates the html options that will be displayed 
// inside of lbUser
private string CreateOption(string text)
{
   string option = "<option>" + text + "</option>"
}

Upvotes: 1

Romil Kumar Jain
Romil Kumar Jain

Reputation: 20775

You need to explicitly bind the datasource on every postback to updated datasource.

Upvotes: 0

Widor
Widor

Reputation: 13275

Yes, you don't necessarily have to use a datasource if you want to add an item explicity:

lbUsers.Items.Add(new ListItem("New Item", "NI"));

Upvotes: 1

Related Questions