Solved

ASP Listbox doesn't show selected Items

Posted on 2010-11-15
3
398 Views
Last Modified: 2012-06-21
Hi,

i created a listbox and filled it with data from a data table. The Listbox is set to multiselect.
If i now select an item, the selected property does not get set for any item.
What am i missing ?


ASP Site 

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="QVSLogoff.aspx.cs" Inherits="QVSLogoff" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">

    <p class="LogoffTitel">
        Schedule User Logoff
    </p>
    <table width="100%">
        <colgroup>
            <col width="33%" />
            <col width="34%" />
            <col width="33%" />
        </colgroup>
        <tr>
            <td align="center" valign="middle" dir="ltr">
                <p>
                    Available PC's in Domain</p>
                <asp:ListBox ID="lbxAvailable" runat="server" Height="100%" Rows="20" 
                    SelectionMode="Multiple" Width="100%">
                    <asp:ListItem>Computer</asp:ListItem>
                </asp:ListBox>
            </td>
            <td align="center" valign="middle" dir="ltr">
                <br />
                <br />
                <br />
                <asp:Button ID="btnAdd" runat="server" Text=">>" onclick="btnAdd_Click" />
                <br />
                <br />
                <br />
                <br />
                <br />
                <asp:Button ID="btnRemove" runat="server" Text="<<" />
                <br />
                <br />
                <br />
                <br />
            </td>
            <td align="center" valign="middle" dir="ltr">
                <p>
                    Selected PC's For Logoff</p>
                <asp:ListBox ID="lbxSelected" runat="server" Height="100%" Rows="20" 
                    SelectionMode="Multiple" Width="100%"></asp:ListBox>
            </td>
        </tr>
    </table>

</asp:Content>


Code Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.DirectoryServices;


public partial class QVSLogoff : System.Web.UI.Page
{

        
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = GetComputerByDisplayName();
        lbxAvailable.DataSource = dt.DefaultView;
        lbxAvailable.DataValueField = "Computer";
        lbxAvailable.DataTextField = "Computer";
        lbxAvailable.DataBind();
        DataTable dtselected = GetSelectedComputer();
        lbxSelected.DataSource = dtselected.DefaultView;
        lbxSelected.DataValueField = "ComputerName";
        lbxSelected.DataTextField = "ComputerName";
        lbxSelected.DataBind();

    }

    protected DataTable GetSelectedComputer()
    {
        dsKTPOIntanetTableAdapters.PCtoLogoffTableAdapter dslogoff = new dsKTPOIntanetTableAdapters.PCtoLogoffTableAdapter();
        dsKTPOIntanet.PCtoLogoffDataTable tbllogoff = new dsKTPOIntanet.PCtoLogoffDataTable();

        dslogoff.Fill(tbllogoff);
        tbllogoff.DefaultView.Sort = "ComputerName";
        return tbllogoff;
    }


    protected DataTable GetComputerByDisplayName()
    {
        DirectoryEntry de = new DirectoryEntry(ConfigurationManager.AppSettings.Get("ADPath"));
        de.Username = ConfigurationManager.AppSettings.Get("ADServiceAccount");
        de.AuthenticationType = AuthenticationTypes.Secure;
        de.Password = ConfigurationManager.AppSettings.Get("ADServiceAccountPassword");
        

        DirectorySearcher directroysearcher = new DirectorySearcher(de);
        directroysearcher.ClientTimeout = TimeSpan.FromSeconds(30);

        //directroysearcher.PropertiesToLoad.Add("name");
        directroysearcher.Filter = "(&(objectClass=Computer))";

        SearchResultCollection searchresults;
        searchresults = directroysearcher.FindAll();
        if(searchresults != null)
        {

        DataTable myTable = new DataTable("ActiveDir");
        DataColumn myCol;
        DataRow myRow;
        myCol = new DataColumn("Computer", System.Type.GetType("System.String"));
        myCol.DefaultValue = "";
        myTable.Columns.Add(myCol);
        

        foreach (SearchResult result in searchresults)
        {
                myRow = myTable.NewRow();
                myRow["Computer"] = result.Properties["name"][0].ToString(); 
                myTable.Rows.Add(myRow);
        }
            myTable.DefaultView.Sort = "Computer";
            return myTable;

        }
        else
        {
            return null;
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        dsKTPOIntanetTableAdapters.PCtoLogoffTableAdapter dslogoff = new dsKTPOIntanetTableAdapters.PCtoLogoffTableAdapter();
        dsKTPOIntanet.PCtoLogoffDataTable tbllogoff = new dsKTPOIntanet.PCtoLogoffDataTable();
        dsKTPOIntanet.PCtoLogoffRow rowlogoff;
        

        string ComputerToAdd = string.Empty;
        foreach (ListItem li in lbxAvailable.Items)
        {
            if(li.Selected)
            {
                rowlogoff = tbllogoff.NewPCtoLogoffRow();
                rowlogoff.ComputerName = li.Value;
                tbllogoff.Rows.Add(rowlogoff);
            }
            
        }
        dslogoff.Update(tbllogoff);
        }

Open in new window

0
Comment
Question by:ktpoitm
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 13

Accepted Solution

by:
devlab2012 earned 500 total points
ID: 34136349
you are binding the listbox everytime on page load. Bind the list box only when Page.IsPostBack is False.
0
 
LVL 1

Author Comment

by:ktpoitm
ID: 34136477
That was it Thank you for your help.
0
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 34136495
I agree with that devlab2012 said above.  Only load the data for the listbox when the page first loads, by running the code that loads the listbox only durring the initial page load.  Otherwise, every time there is a postback, the listbox will get reset as it is reloaded with data and you will loose all of your selected items.  Do something like the code below.
public partial class Default8 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadComputerListboxs();
        }
    }

    private void LoadComputerListboxs()
    {
        DataTable dt = GetComputerByDisplayName();
        lbxAvailable.DataSource = dt.DefaultView;
        lbxAvailable.DataValueField = "Computer";
        lbxAvailable.DataTextField = "Computer";
        lbxAvailable.DataBind();
        DataTable dtselected = GetSelectedComputer();
        lbxSelected.DataSource = dtselected.DefaultView;
        lbxSelected.DataValueField = "ComputerName";
        lbxSelected.DataTextField = "ComputerName";
        lbxSelected.DataBind();
    }
}

Open in new window

0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Suggested Courses

631 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question