Solved

ASP Listbox doesn't show selected Items

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

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…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

785 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