Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从GridView列中选择多个列表框项_C#_Asp.net_Gridview_Listbox - Fatal编程技术网

C# 从GridView列中选择多个列表框项

C# 从GridView列中选择多个列表框项,c#,asp.net,gridview,listbox,C#,Asp.net,Gridview,Listbox,我有一个启用了Multiselect的数据绑定列表框。在页面加载时,我从GridView列中输入信息,并使用以下代码选择所有匹配的选项: string[] separators = { "<br />" }; String Departments = Session["ProjDept"].ToString(); string[] splitDepartments = Departments.Split(separators, StringSplitOptions.RemoveEm

我有一个启用了Multiselect的数据绑定列表框。在页面加载时,我从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));
        }
然而,我遇到了一个奇怪的问题:当GridView列中只有一个部门时,列表框中的选项会被正确选择,但当有多个部门时,只有最后一个部门会被选择

我已经在foreach中运行了System.Diagnostics.Debug.Printdept,以确保所有的值都被传递,并且它们都出现在标准输出中,但列表框仍然不配合

关于如何解决这个问题,或者,我可以使用什么其他代码来实现相同的结果


谢谢大家!

SelectedIndex属性一次只允许一个值,因此每次迭代都要重置它。这就是为什么只选择最后一个。您需要从ListItem本身访问所选属性

如果不亲自尝试,它应该看起来像:

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

只要您有SelectionMode=Multiple,代码就应该可以工作。

SelectedIndex属性一次只允许一个值,因此每次迭代都会重置它。这就是为什么只选择最后一个。您需要从ListItem本身访问所选属性

如果不亲自尝试,它应该看起来像:

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

只要你有SelectionMode=Multiple,代码就应该可以工作。

是的,你得到了!我想是那样的,但无法指出失败的确切原因。。。非常感谢。是的,你明白了!我想是那样的,但无法指出失败的确切原因。。。非常感谢。