Alexking2005
Alexking2005

Reputation: 315

C# WPF - Get the selected items from a ListView

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.

When one item is selected on my listview named lstInterrogateur, i get the ID like that:

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:

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?

Thanks.

Upvotes: 0

Views: 13389

Answers (1)

Clemens
Clemens

Reputation: 128061

You can't use SelectedIndex to get each item in the loop over SelectedItems. Instead, access them by the loop variable:

foreach (var item in lstMatiereInterrogateur.SelectedItems)
{                    
    CompRow = item as DataRowView;
    idMatiere = Convert.ToInt16(CompRow["idMatiere"]);
    ...
}

Similarly you could use SelectedItem instead of SelectedIndex to access a single selected item:

CompRow = lstInterrogateur.SelectedItem as DataRowView;
idInterrogateur = Convert.ToInt16(CompRow["idInterrogateur"]);

Upvotes: 1

Related Questions