Solved

ASP Listbox doesn't show selected Items

Posted on 2010-11-15
3
396 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

733 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