简体   繁体   中英

System.InvalidCastException while looping through GridView.SelectedItems

I am writing a Windows 8 app (XAML-C#-Windows Store app (metro)) where I have to loop through a GridView's SelectedItems collection.

Here is my code:

private void bottomAppBarBotonEliminar_Tapped(object sender, TappedRoutedEventArgs e)
{
    //Borrar el(los) elemento(s) seleccionado(s)
    foreach (GridViewItem elItem in GVElementos.SelectedItems)
    {
        MiColeccion.RemoveAt(GVElementos.Items.IndexOf(elItem));
    }
    ElementoSQL.Sincronizar(MiColeccion);
}

When I run it and that method is fired, I get the following error (translated from Spanish):

An exception of type 'System.InvalidCastException' occurred 
in Lista.exe but was not handled in user code
Additional information: Unable to convert an object of 
type 'System.String' to the type 'Windows.UI.Xaml.Controls.GridViewItem'.

When the program breaks, Visual Studio highlights the line with the foreach statement.

"GVElementos" is a XAML GridView.
Isn't "elItem" of type "GridViewItem" and "GVElementos.SelectedItems" a collection of elements of type "GridViewItem"?
What am I doing wrong? Is there another way to iterate the GridView? I come from ASP.NET where this way of doing it makes sense.

That exception is really explicit. You should pay attention to the message instead of pasting code from a previous working implementation. Specially if your implementation is from another framework or environment!

Basically as the guys suggested on the comments of your question and as the exception states you are doing an invalid cast from string to GridViewItem.

Try doing the following:

foreach (string elItem in GVElementos.SelectedItems)
{
     MiColeccion.RemoveAt(GVElementos.Items.IndexOf(elItem));
}

If you read the documentation of the controls you'll understand that each item is a string object.

Here's a quickstart link: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh780650.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

And here's a more concrete example: http://code.msdn.microsoft.com/windowsapps/ListViewSimple-d5fc27dd

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