简体   繁体   中英

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

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;

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM