[英]how to get the selected values of Listbox in c#
我已經綁定了列表框,其中列表框的數據源是列表。如何在列表框中獲取選定列表項的選定值,我的示例代碼如下
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()));
}
}
任何人都可以解決我的問題。
首先,列表的Count
永遠不能小於零。 始終>= 0
。
然后,當您對列表進行數據綁定時,這些項目通常是DataRowView
類型的(應該可以通過調試應用程序進行驗證)。 如果正確,則必須將每個選定的項目DataRowView
為DataRowView
,然后將其Row
屬性的值DataRowView
為所需的類型。
我只是注意到,在以下循環中,您甚至沒有使用選定的項,而是始終使用SelectedValue
:
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(int.Parse(lstCompanies.SelectedValue.ToString()));
}
嘗試將其更改為:
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(((<WhatEverClassYouUse>)lstCompanies.SelectedItems[i]).CompanyID);
}
說明:如果選擇了列表中的多個項目,則將這些項目添加到SelectedItems
集合中。 您可以迭代這些項目。 每個項目將是DataRowView
的對象(將數據綁定到DataTable
或DataView
)或集合中的類。
正如您沒有告訴我們GetPredefinedDetails
返回的對象類型GetPredefinedDetails
,我將其替換為WhatEverClassYouUse
。 將此類型轉換為正確的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.