简体   繁体   中英

how to get the selected values of Listbox in c#

i had bind the listbox where datasource of listbox is list.how can i get the selected value of selected list item in listbox.my sample code as follows

        pdfList = attendanceDetailsPresenter.GetPredefinedDetails();
        this.lstCompanies.DataSource = pdfList;
        this.lstCompanies.DisplayMember = "CompanyName";
        this.lstCompanies.ValueMember = "CompID";

        this.lstDepartments.BindingContext = new BindingContext();
        this.lstDepartments.DataSource = pdfList;
        this.lstDepartments.DisplayMember = "DepartmentName";
        this.lstDepartments.ValueMember = "DeptID";

       if (lstCompanies.SelectedItems.Count < 0)
        {
            MessageBox.Show("Please Select Any one Company");
            return attendanceCalculationDetailsDataList;
        }
        else
        {
            for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
            {
               attendanceCalculationDetailsData.CompanyID.Add(int.Parse(lstCompanies.SelectedValue.ToString()));
            }
        }

can anyone solve my problem please.

First of all, the Count of a list can never be less than zero. It's always >= 0 .

Then, when you data-bind your list, the items usually are of type DataRowView (which you should be able to verify by debugging your application). If that is right, you should have to cast each selected item to DataRowView and then cast the value of its Row property to the type you expect.


I just noticed that in the following loop you're not even using the selected items, but always the SelectedValue :

for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
    attendanceCalculationDetailsData.CompanyID.Add(int.Parse(lstCompanies.SelectedValue.ToString()));
}

Try changing this to:

for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
    attendanceCalculationDetailsData.CompanyID.Add(((<WhatEverClassYouUse>)lstCompanies.SelectedItems[i]).CompanyID);
}

Explanation: If more than one item in the list are selected, the items are added to the SelectedItems collection. You can iterate these items. Each item will be an object of DataRowView (when data bound to a DataTable or DataView ) or a class in a collection.

As you didn't tell us the type of objects returned by GetPredefinedDetails , I substituted it with WhatEverClassYouUse . Cast this to the right type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM