C# WPF - 从 ListView 中获取所选项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20901042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# WPF - Get the selected items from a ListView
提问by Alexking2005
I have a listview with multiple columns. The data are binding with a DataView. The first column is the ID, the second column is the name.
我有一个多列的列表视图。数据与 DataView 绑定。第一列是 ID,第二列是名称。
When one item is selected on my listview named lstInterrogateur, i get the ID like that:
当在我的名为 lstInterrogateur 的列表视图中选择一项时,我会得到这样的 ID:
DataRowView CompRow;
string InsertQuery = "INSERT INTO interrogateur_matiere (idinterrogateur_matiere, idMatiere, idInterrogateur) VALUES ";
int SComp, i=1, total;
long idInterrogateur, idMatiere;
SComp = lstInterrogateur.SelectedIndex;
CompRow = lstInterrogateur.Items.GetItemAt(SComp) as DataRowView;
idInterrogateur = Convert.ToInt16(CompRow["idInterrogateur"]);
And when multiple items are selected on my listview named lstMatiereInterrogateur, i get the ID like that:
当在我的名为 lstMatiereInterrogateur 的列表视图上选择多个项目时,我会得到这样的 ID:
total = lstMatiereInterrogateur.SelectedItems.Count;
foreach (var item in lstMatiereInterrogateur.SelectedItems)
{
SComp = lstMatiereInterrogateur.SelectedIndex;
CompRow = lstMatiereInterrogateur.Items.GetItemAt(SComp) as DataRowView;
idMatiere = Convert.ToInt16(CompRow["idMatiere"]);
InsertQuery += "(NULL, '" + idInterrogateur + "', '" + idMatiere + "')";
if (total != i)
InsertQuery += ", ";
i++;
}
}
But then i only get the last ID. For exemple, i selected 2 items ID=3 et ID=5, i will get 2 times ID=5. Why?
但后来我只得到最后一个ID。例如,我选择了 2 个项目 ID=3 和 ID=5,我将得到 2 次 ID=5。为什么?
Thanks.
谢谢。
回答by Clemens
You can't use SelectedIndexto get each item in the loop over SelectedItems. Instead, access them by the loop variable:
您不能用于SelectedIndex获取循环中的每个项目 over SelectedItems。相反,通过循环变量访问它们:
foreach (var item in lstMatiereInterrogateur.SelectedItems)
{
CompRow = item as DataRowView;
idMatiere = Convert.ToInt16(CompRow["idMatiere"]);
...
}
Similarly you could use SelectedIteminstead of SelectedIndexto access a single selected item:
同样,您可以使用SelectedItem而不是SelectedIndex访问单个选定项目:
CompRow = lstInterrogateur.SelectedItem as DataRowView;
idInterrogateur = Convert.ToInt16(CompRow["idInterrogateur"]);

