Solved

ASP Listbox doesn't show selected Items

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
ASP.net See list of pdf documents in folder and read 2 28
Align Buttons next to each other 2 25
Asp.net mvc foreach 3 32
Ajax Panel Not Updating When Triggered By Timer 4 37
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
Concerto provides fully managed cloud services and the expertise to provide an easy and reliable route to the cloud. Our best-in-class solutions help you address the toughest IT challenges, find new efficiencies and deliver the best application expe…

919 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now