我有一個列表框,其顯示器件是公司名稱和值的會員是CompanyIDC#獲得所有項目的值在列表框中
我想所有公司的ID的(不僅僅是selecteditems)一些詮釋與價值觀for循環確定項目的索引。
我該怎麼做? 在此先感謝。
我有一個列表框,其顯示器件是公司名稱和值的會員是CompanyIDC#獲得所有項目的值在列表框中
我想所有公司的ID的(不僅僅是selecteditems)一些詮釋與價值觀for循環確定項目的索引。
我該怎麼做? 在此先感謝。
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
}
謝謝你的工作(y) – Sabri
因此,您的數據綁定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();
不知道標的項目的類型,你必須使用一些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();
注意,代碼是適用前提您的ListBox
的DataSource
不是DataTable
,因爲在這種情況下,ValueMember
是ColumnName
,而不是屬性名稱。在這種情況下,你可以做這樣的事情:
//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();
你嘗試過什麼? – Viva
什麼樣的應用程序,您的目標是winform/wpf網站? – Habib