2015-02-09 50 views
0

我有一个postcodeitems列表,我将它绑定到列表框。 它包含两个属性:邮编,区域。自定义对象列表框Foreach循环

我想遍历列表框项目,如果选择了项目,请将postcodeitem对象添加到另一个列表。

  List<Valueobjects.postcodeitem> temp = _BL.GetPostCodeAreasFromZones(); 
      PCList.AddRange(temp); 
      ListBox1.DataSource = PCList; 
      ListBox1.DataBind(); 


List<Valueobjects.postcodeitem> postcodecollection = new List<Valueobjects.postcodeitem>(); 

foreach (ListItem listitem in ListBox1.Items) 
{ 
    if (listitem.Selected) 
    { 
     i = i + 1; 

     //Run at 20 to speed up query 
     if (i == 20) 
     { 
      //Get data 
      CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2)); 
      i = 0; 
      } 
      else 
      { 
       //add the post code to temp list 
       postcodecollection.Add(listitem); 
      } 
     } 
    } 

    if (i > 0) 
    { 
     //get data 
     CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2)); 
    } 
} 

很明显,我试图添加(listitem)不会去工作,因为这是一个列表项,而不是一个postcodeitem。我的问题是如何在选择列表项目的列表中获取postcodeitem对象?

感谢

+0

下次您提问时,请格式化您的问题。这是非常难以阅读。你的问题格式化越好,你会得到更多答案,记住这一点。 – Complexity 2015-02-09 10:33:36

+0

你可以发布你将ListBox1.Items绑定到数据源的代码吗? – 2015-02-09 10:35:24

+1

它可以像这样简单:postcodecollection.Add((Valueobjects.postcodeitem)listitem); – 2015-02-09 10:36:34

回答

1

尝试类似以下。

IList<Employee> boundList = ListBox1.DataSource 
var obj = boundList[ListBox1.SelectedIndex] 

更新 =>我没有测试的代码,但像下面的东西。使用for循环来跟踪元素索引。

for (int i = 0; i< ListBox1.Items.Length; i++) 
{ 
    if (ListBox1.Items[i].Selected) 
    { 
     i = i + 1; 

     //Run at 20 to speed up query 
     if (i == 20) 
     { 
      //Get data 
      CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2)); 
      i = 0; 
      } 
      else 
      { 
       //add the post code to temp list 
       postcodecollection.Add(ListBox1.DataSource.ToList().ElementAt(i)); 
      } 
     } 
    } 

    if (i > 0) 
    { 
     //get data 
     CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2)); 
    } 
} 

反正这不是建议的方式。您应该获取选定的值并使用该选定值(唯一字段)从任何持久性存储器(如数据库)中获取相关数据。

+0

但是,我收到错误:错误无法将类型'System.Web.UI.WebControls.ListItem'转换为'GeoLocation.Classes.Valueobjects.postcodeitem' – user4316519 2015-02-09 10:40:47

+0

@ user4316519更新了我的答案。 – 2015-02-09 10:48:58

+0

谢谢,我该如何将它应用于我的代码? – user4316519 2015-02-09 11:12:16