Topic: How to add two ASP.Net listboxes to manage collections using javascript within AJAX controls
Share/Save/Bookmark

Description: This tutorial shows you how to add two listboxes that you can use to manage a collection.  One might be the collection tied to an object and the other a list that you can choose from to add to your collection.  (e.g. Company Users and user's that are administrators)  These listboxes reside within AJAX update panels.


 1.  Add the following markup to your aspx page
     a.  Make sure your Page tag has the following attributes set
         <%@ Page Language="VB" AutoEventWiring="false" CodeFile="MyClass.aspx.vb" Inherits="MyClass" EnableEventValidation="false" %>
     b.  Make sure your AjaxControlToolkit is registerer.
         <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AjaxToolkit" %>
     c.  Make you have a DOCTYPE declaration that has XHTML Transitional like the one below
         <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional??EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     d.  I put all of the javascript in code behind files.  You can do the same, or add it to the markup when we get to that section, below is the path to my javascript files located between my <head> tags.
          <script src="subs/functions.js" type="text/javascript" language="javascript" />
     e.  On your page, at the top preferrably, add a Ajax Script Manager.
          <asp:SrcriptManager ID="ScriptManager1" runat="server" />
     f.  Add the markup below to get your UpdatePanels and ListBoxes
     <asp:UpdatePanel ID="uPnlMain" runat="server" UpdateMode="conditional">
        <ContentTemplate>

           <tr id="trSomeObject" runat="server" visible="false">
              <td>
                 <div>
                    <!-- start pnlUser -->
                       <asp:Panel ID="pnlUser" runat="server">
                          <table cellpadding="0" cellspacing="0" width="100%">
                             <tr>
                                <td>
                                   <table cellpadding="0" cellspacing="0" width="100%">
                                      <tr>
                                         <td>
                                             <table cellpadding="0" cellspacing="0">
                                                <tr>
                                                   <td>
                                                      <table class="ClassWithTopBottomLine" cellspacing="0" cellpadding="10" width="534px">
                                                         <tr>
                                                            <td colspan="2" style="padding-bottom: 0px">
                                                               Use the lists below to manage the User(s) for your SomeObject.
                                                            </td>
                                                         </tr>
                                                         <tr>
                                                            <td align="center">
                                                               <table cellspacing="0" cellpadding="0">
                                                                  <tr>
                                                                     <td align="left">
                                                                        <asp:Label ID="lblUserCompany" runat="server" CssClass="ClassForFields" Width="140px">Available User(s)</asp:Label>
                                                                     </td>
                                                                     <td>
                                                                     </td>
                                                                     <td>
                                                                     </td>
                                                                     <td>
                                                                     </td>
                                                                     <td align="left">
                                                                        <asp:Label ID="lblUsersSomeObject" runat="server" CssClass="ClassForFields" Width="140px">Current User(s)</asp:Label>
                                                                     </td>
                                                                  </tr>
                                                                  <tr>
                                                                     <td class="right">
                                                                        <asp:ListBox ID="lstAllUsers" name="lstAllUsers" runat="server" ondblclick="thisListItemASPNet('lstAllUsers', 'lstSelected');" class="content2" style="width: 230px; height: 100px" multiple="true"/>
                                                                     </td>
                                                                     <td width="5">
                                                                        <img src="images/spacer.gif" alt="" />
                                                                     </td>
                                                                     <td class="middle">
                                                                        <table style="color: Blue" cellspacing="0" cellpadding="2" border="0">
                                                                           <tr>
                                                                              <td>
                                                                                 <img id="imgAdd" onclick="thisListItemASPNet('lstAllUsers', 'lstSelected');" src="images/RightSingleArrow.gif" border="0" name="imgAdd" alt="" />
                                                                              </
td>
                                                                           </tr>
                                                                           <tr>
                                                                              <td>
                                                                                 <img id="imgAddAll" onclick="selectAllItemsASPNet('lstAllUsers', 'lstSelected');" src="images/RightDoubleArrow.gif" border="0" name="imgAddAll" alt="" />
                                                                              </
td>
                                                                           </tr>
                                                                           <tr>
                                                                              <td>
                                                                                 <img id="imgRemoveAll" onclick="selectAllItemsASPNet('lstSelected', 'lstAllUsers');" src="images/LeftDoubleArrow.gif" border="0" name="imgRemoveAll" alt="" />
                                                                              </
td>
                                                                           </tr>
                                                                           <tr>
                                                                              <td>
                                                                                 <img id="imgRemove" onclick="thisListItemASPNet('lstSelected', 'lstAllUsers');" src="images/LeftSingleArrow.gif" border="0" name="imgRemove" alt="" />
                                                                              </
td>
                                                                           </tr>
                                                                        </table>
                                                                     </td>
                                                                     <td>
                                                                        <asp:ListBox ID="lstSelected" name="lstSelected" runat="server" ondblclick="thisListItemASPNet('lstAllUsers', 'lstSelected');" class="content2" style="width: 230px; height: 100px" multiple="true"/>
                                                                     </td>
                                                                  </tr>
                                                               </table>
                                                            </td>
                                                         </tr>
                                                         <tr class="center" id="trUsersError" runat="server" visible="false">
                                                            <td colspan="2" style="height: 22px">
                                                               <asp:Label ID="lblUsersError" runat="server" CssClass="required">
                                                                  Please select User(s).
                                                               </asp:Label>
                                                            </td>
                                                         </tr>
                                                      </table>
                                                   </td>
                                                </tr>
                                             </table>
                                          </td>
                                       </tr>
                                    </table>
                                 </td>
                              </tr>
                           </table>
                        </asp:Panel>
                        <!-- end pnlUser -->
                     </div>
                  </td>
               </tr>
            </table>
         </ContentTemplate>
      </asp:UpdatePanel>

2.  In your JavaScript code behind file, add the following functions.  These are the functions that are wired to the Listboxes and Image Buttons.          
     function
thisListItemASPNet (strBox1, strBox2)
     {
        var box1 = document.getElementById(strBox1);
        var box2 = document.getElementById(strBox2);

        for (var i=0; i < box1.options.length; i++)
        {
           if (box1.options[i].selected)
           {
              box2.options[box2.options.length] = new Option (box1.options[i].text, box1.options[i].value, false, false);
           }
        for (var i = box1.options.length - 1; i >= 0; i--)
        {
           if (box1.options[i].selected)
           {
              box1.options[i] = null;
           }
        }
     }      

     function selectAllitemsASPNet (selectList, newList)
     {
        var box1 = document.getElementById(selectList);
        var box2 = document.getElementById(newList);
        if (box1.options.length == 0)
           return;
        for (var i=0; i < box1.options.length; i++)
        {
           box1.options[i].selected = true;
        }
        thisListItemASPNet (box1.name, box2.name);
     }

3.  To Load the collection into the listboxes, use a method similar to the one below to populate them.
     Sub LoadUsers()
        Dim redirect As Boolean = False
        Dim userBLL As New MyBusinessLayerObject.UserBLL
        Dim UsersToSelectFrom As MyModelLayerObject.UserCollection
        Dim UsersCurrent As MyModelLayerObject.UserCollection
       
        Try
           UsersToSelectFrom = userBLL.GetUsersToSelectFrom(Some method to get Users in Company not in Selected List)
           UsersCurrent = userBLL.GetUsersAlreadySelected(Some method to get Users already selected)

           lstAllUsers.Items.Clear()
           lstAllUsers.DataSource = UsersToSelectFrom
           lstAllUsers.DataTextField = "FullName"
           lstAllUsers.DataValueField = "UserID"
           lstAllUsers.DataBind()

           lstSelected.Items.Clear()
           lstSelected.DataSource = UsersCurrent
           lstSelected.DataTextField = "FullName"
           lstSelected.DataValueField = "UserID"
           lstSelected.DataBind()

        Catch ex As Exception
           -- Some type of Exception Manager call should be made here           redirect = True
        Finally
           userBLL = Nothing
           UsersToSelectFrom = Nothing
           UsersCurrent = Nothing
        End Try
        If redirect Then
           Response.Redirect("error.aspx", False)
        End If
     End Sub
             
4.  The next method is how you get the data out of the Listbox and use it to update some object
   Dim selList() As String
   Dim userColl As MyModelLayerObject.UserCollection

   selList = Split(Request.Form("lstSelected"), ",")


   If selList(0) = String.Empty Then

      -- show some error that states you need a user

   End If

   -- Populate a User Collection from the Listbox

   For i As Integer = 0 To selList.Length - 1
      user = New MyModelLayerObject.User

      user.UserID = CInt(selList(i))

      userColl.Add(user)
   Next
   -- Use the collection in some method to update the database