jpavlov
jpavlov

Reputation: 2261

Selecting listbox items from a previously selected listbox

I have two list boxes, I am trying to automatically select the second list from from the first one. The trouble is, I get stuck in the second Foreach loop, and the first one doesn't run insync with it. Can someone take a look, thanks.

        foreach (ListItem item in this.clb_Departments.Items)
        {
            foreach (ListItem it in this.cbl_fDepartments.Items)
            {
                    if (item.Value == "2")
                    {
                        if (it.Value == "2")
                        {
                            if (item.Selected == true)
                            {
                                it.Selected = true;
                                break;
                            }
                        }
                    }
                    if (item.Value == "3")
                    {
                        if (it.Value == "3")
                        {
                            if (item.Selected == true)
                            {
                                it.Selected = true;
                            }
                        }
                    }
            } 

Upvotes: 0

Views: 232

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460018

If both ListBoxes have the same items:

for(int i=0; i<cbl_fDepartments.Items.Count; i++)
    cbl_fDepartments.Items[i].Selected = clb_Departments.Items[i].Selected;

Upvotes: 3

Abe Miessler
Abe Miessler

Reputation: 85036

I'm still a bit confused on what you are trying to do but this might get you started?

    foreach (ListItem item in this.clb_Departments.Items)
    {
        this.cbl_fDepartments.Items[this.cbl_fDepartments.IndexOf(item)].Selected = item.Selected;
    }

If that doesn't work you can try this inside of your foreach instead:

this.cbl_fDepartments.Items.Cast<ListItem>().Where(t=>t.Value == item.Value).Selected = item.Selected;

Upvotes: 0

Roman Royter
Roman Royter

Reputation: 1665

I don't think this is the right approach. Once you capture the data from the first list box on the first page, you stash it somewhere. Then when you render the review page, you set the SelectedValue of the second list box with the value you stashed previously.

There is no need to synchronize anything.

Upvotes: 0

Related Questions