简体   繁体   English

从GridView列中选择多个ListBox项

[英]Selecting Multiple ListBox items from GridView column

I have a databound Listbox with Multiselect enabled. 我有一个启用了Multiselect的数据绑定列表框。 On page load, I feed the information from a GridView column and select all the options that match, using this code: 在页面加载时,我使用GridView列提供信息,并使用以下代码选择所有匹配的选项:

string[] separators = { "<br />" };

String Departments = Session["ProjDept"].ToString();
string[] splitDepartments = Departments.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var dept in splitDepartments)
        {
            listDepartment.SelectedIndex = listDepartment.Items.IndexOf(listDepartment.Items.FindByText(dept));
        }

However, I am running into a strange issue: when there is only one department in the GridView column, the option in the listbox gets properly selected, but when there's multiple departments only the LAST department gets selected. 但是,我遇到了一个奇怪的问题:当GridView列中只有一个部门时,将正确选择列表框中的选项,但是当有多个部门时,只会选择LAST部门。

I've ran System.Diagnostics.Debug.Print(dept) within my foreach to ensure that all the values are getting passed and they all appear in the STDOUT, but the listbox still won't cooperate. 我已经在我的foreach中运行了System.Diagnostics.Debug.Print(dept)来确保所有值都已传递并且它们都出现在STDOUT中,但是列表框仍然无法配合。

Any ideas as to how I can fix this -- or alternatively, what other code could I use to achieve the same results? 关于如何解决此问题的任何想法-或者,我可以使用什么其他代码来实现相同的结果?

Thank you! 谢谢!

The SelectedIndex property only allows one value at a time, so you're resetting it with each iteration. SelectedIndex属性一次仅允许一个值,因此您需要在每次迭代时将其重置。 That's why only the last one is being selected. 这就是为什么仅选择最后一个。 You need to access the "Selected" property from the ListItem itself. 您需要从ListItem本身访问“ Selected”属性。

Without trying it myself, it should look something like: 无需亲自尝试,它应该类似于:

foreach (var dept in splitDepartments)
{
     int index = listDepartment.Items.IndexOf(listDepartment.Items.FindByText(dept));        
     listDepartment.Items[index].Selected = true;
}

As long as you do have SelectionMode="Multiple" - that code should work. 只要您确实具有SelectionMode =“ Multiple”-该代码就可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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