C#get列表框中所有项目的值

时间:2013-11-22 14:20:29

标签: c# winforms listbox

我有一个列表框,其显示成员是CompanyName,Value Member是CompanyID

我想通过for循环确定项目的索引,将所有公司的ID(不仅仅是选定项目)转换为某些Int值。 C#winforms application。

可能看起来像这样的东西。

for (int i = 0; i < listBox1.Items.Count; i++)
            {
              int ID =  Convert.ToInt32(listBox1.Items[i].GetType().GetProperty("ValueMember").ToString());
            }

3 个答案:

答案 0 :(得分: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 :(得分: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();

答案 2 :(得分: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();

请注意,仅当DataSource的{​​{1}}不是ListBox时,该代码才适用,因为在这种情况下,DataTableValueMember,而非属性名称。在这种情况下,你可以这样做:

ColumnName