user11075296
user11075296

Reputation: 13

System.InvalidCastException with ListView in Xamarin.Forms

I am currently creating an application for IOS and Android with Xamarin.Forms that takes a reservation and puts the reservation information into an SQLite database which then will populate into a ListView for an admin to either delete or accept the reservation. The database works fine but I get a "Specified cast is not valid" error when trying to view the admin page with the ListView of reservations. The code is below:

I have tried to research the issue and I am thinking it has to do with the in XAML code and the binding context, but am not sure what to do to fix it.

MyPage.XAML

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Assignment6.MyPage">
    <ContentPage.Content>
        <StackLayout>
            <ListView x:Name = "ListviewItems" />
            <ListView.ItemTemplate>
                <DataTemplate>
                  <ViewCell>
                        <ViewCell.View>
                            <StackLayout>
                            <Label Text = "{Binding date}" />
                            <Label Text = "{Binding meetingLocation}" />
                                </StackLayout>
                      </ViewCell.View>
                        </ViewCell>   
                    </DataTemplate>
                </ListView.ItemTemplate>
            </StackLayout>

    </ContentPage.Content>
</ContentPage>

MyPage.XAML.CS

namespace Assignment6
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MyPage : ContentPage
    {
        private ObservableCollection<Reservation> items = new ObservableCollection<Reservation>();
        public MyPage()
        {
            InitializeComponent();

            Init();

        }

        public void Init()
        {
            BindingContext = new Reservation();
            var enumerator = App.UserDatabase.GetReservation();

            while (enumerator.MoveNext())
            {
                items.Add(enumerator.Current);
            }
            ListviewItems.ItemsSource = items;


        }
    }
}

Reservation.CS

public class Reservation
    {
        [PrimaryKey][AutoIncrement]
        public int date { get; set; }
        public int startingTime { get; set; }
        public string duration { get; set; }
        public int meetingLocation { get; set; }


        public Reservation()
        {
        }

        public Reservation(int date, int startingTime, string duration, int meetingLocation)
        {
            this.date = date;
            this.startingTime = startingTime;
            this.duration = duration;
            this.meetingLocation = meetingLocation;


        }
    }

Method from MainPage.XAML.CS that adds the reservation from a datepicker, time picker, slider and drop down menu.

void Handle_Clicked(object sender, System.EventArgs e)
        {
            DisplayAlert("Reservation", "Your reservation for a " + Output.Text + " meeting in room " + Room.SelectedIndex +
                 " starting at " + Time.Time + " on " + Date.Date.Month + "/" + Date.Date.Day + "/" + " " + Date.Date.Year + " for " + Slide.Value.ToString() + " hours has been added.", "OK");
        Reservation reserve = new Reservation(Date.Date.Month, Time.Time.Hours, Slide.Value.ToString(), Room.SelectedIndex);


        App.UserDatabase.SaveReservation(reserve);


    }

GetReservation Method:

 public IEnumerator<Reservation> GetReservation()
        {
            lock (locker)
            {
                if (database.Table<Reservation>().Count() == 0)
                {
                    return null;
                }
                else
                {
                    return database.Table<Reservation>().GetEnumerator();
                }
            }
        }

MainPage button clicked method which takes the user to the admin page with List View:

 async void Handle_Clicked_1(object sender, System.EventArgs e)
        {
            await Navigation.PushAsync(new MyPage());

        }

When I run the program, I get the following error "System.InvalidCastException" specified cast is not valid. Below is the StackTrace:

System.InvalidCastException: Specified cast is not valid.
  at Xamarin.Forms.ItemsView`1+<>c[TVisual].<.cctor>b__24_0 (Xamarin.Forms.BindableObject b, System.Object v) [0x00000] in D:\a\1\s\Xamarin.Forms.Core\ItemsView.cs:25
  at Xamarin.Forms.BindableObject.SetValueCore (Xamarin.Forms.BindableProperty property, System.Object value, Xamarin.Forms.Internals.SetValueFlags attributes, Xamarin.Forms.BindableObject+SetValuePrivateFlags privateAttributes) [0x00071] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:387
  at Xamarin.Forms.BindableObject.SetValue (Xamarin.Forms.BindableProperty property, System.Object value, System.Boolean fromStyle, System.Boolean checkAccess) [0x0003d] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:573
  at Xamarin.Forms.BindableObject.SetValue (Xamarin.Forms.BindableProperty property, System.Object value) [0x00000] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:99
  at Assignment6.MyPage.InitializeComponent () [0x00023] in /Users/zane/Projects/Assignment6/Assignment6/obj/Debug/netstandard2.0/MyPage.xaml.g.cs:26
  at Assignment6.MyPage..ctor () [0x00013] in /Users/zane/Projects/Assignment6/Assignment6/MyPage.xaml.cs:16
  at Assignment6.MainPage+<Handle_Clicked_1>d__2.MoveNext () [0x0000f] in /Users/zane/Projects/Assignment6/Assignment6/MainPage.xaml.cs:33
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.13/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1023
  at Foundation.NSAsyncSynchronizationContextDispatcher.Apply () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.13/src/Xamarin.iOS/Foundation/NSAction.cs:178
  at at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
  at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.13/src/Xamarin.iOS/UIKit/UIApplication.cs:79
  at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0002c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.13/src/Xamarin.iOS/UIKit/UIApplication.cs:63
  at Assignment6.iOS.Application.Main (System.String[] args) [0x00001] in /Users/zane/Projects/Assignment6/Assignment6.iOS/Main.cs:17

Any help with this would be greatly appreciated! I have been trying to debug this for awhile but I can't seem to figure out what the issue is.

Upvotes: 1

Views: 2671

Answers (1)

Jason
Jason

Reputation: 89102

your ItemTemplate needs to be nested inside of your ListView block

      <ListView x:Name = "ListviewItems" >
        <ListView.ItemTemplate>
            <DataTemplate>
              <ViewCell>
                    <ViewCell.View>
                        <StackLayout>
                        <Label Text = "{Binding date}" />
                        <Label Text = "{Binding meetingLocation}" />
                            </StackLayout>
                  </ViewCell.View>
                    </ViewCell>   
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>

Upvotes: 1

Related Questions