user4316519
user4316519

Reputation: 33

Custom Objects Listbox Foreach Loop

I have a list of postcodeitems and I bind this to a listbox. It contains two properties : postcode, area.

I want to loop through the listbox items and if the item is selected, add the postcodeitem object to another list.

            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));
    }
}

Obviously where I am trying to add (listitem) isnt going to work as this is a list item and not a postcodeitem. My question is how do I get the postcodeitem object within the list where the list item is selected?

thanks

Upvotes: 0

Views: 483

Answers (1)

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

Try something like following.

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

Update => I have not tested the code but something like following. Using for loop to track the element index.

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));
    }
}

Anyways this is not recommended way. You should get selected value and use that selected value(unique field) to fetch relevant data from any persistant storage like database.

Upvotes: 1

Related Questions