Solved

ASP Listbox doesn't show selected Items

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
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…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

747 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

16 Experts available now in Live!

Get 1:1 Help Now