2013-11-22 96 views
-3

我有一個列表框,其顯示器件是公司名稱和值的會員是CompanyIDC#獲得所有項目的值在列表框中

我想所有公司的ID的(不僅僅是selecteditems)一些詮釋與價值觀for循環確定項目的索引。

我該怎麼做? 在此先感謝。

+1

你嘗試過什麼? – Viva

+3

什麼樣的應用程序,您的目標是winform/wpf網站? – Habib

回答

3
foreach (DataRowView drv in listBox1.Items) 
     { 
      int id= int.Parse(drv.Row[listBox1.ValueMember].ToString()); 
      //if you want to store all the idexes from your listbox, put them into an array 
     } 
+1

謝謝你的工作(y) – Sabri

0

因此,您的數據綁定IEnumerable<Company>ListBox

那麼這應該工作:

int[] ids = new[]{ 1, 2, 3 }; 
int[] indices = listbox1.Items.Cast<Company>() 
    .Select((company, index) => new { company, index}) 
    .Where(x => ids.Contains(x.company.ID)) 
    .Select(x => x.index) 
    .ToArray(); 
0

不知道標的項目的類型,你必須使用一些Reflection這樣的:

//Suppose your companyId is int 
var valueMember = listBox1.Items[0].GetType().GetProperty(listBox1.ValueMember); 
var companyIds = listBox1.Items.Cast<object>() 
         .Select(o=>(int)valueMember.GetValue(o,null)) 
         .ToList(); 

注意,代碼是適用前提您的ListBoxDataSource不是DataTable,因爲在這種情況下,ValueMemberColumnName,而不是屬性名稱。在這種情況下,你可以做這樣的事情:

//In the case of using DataTable, the underlying item is a DataRowView 
var companyIds = listBox1.Items.Cast<DataRowView>() 
         .Select(row=>(int)row.Row[listBox1.ValueMember]) 
         .ToList(); 
相關問題