DataGrid foreach entity error

102 Views Asked by At

In this _ControlAvailable I am getting an error. In my entity "InsuranceQuotation c" (which is my db GridView) I have access to "c.mYear" which is a column containing dates. This from db gives me "InsuranceQuotation.mYear" like this:

void EditableCustomersGrid_ControlAvailable(object sender, ControlAvailableEventArgs e)
    {
        List<int> ageList = new List<int>();
        if (e.Control is DataGrid)
        {
            DataGrid dg = (DataGrid)e.Control;

            // error here "InsuranceQuotation c"
            foreach (InsuranceQuotation c in dg.ItemsSource)
            {
                var yom = c.mYear;
                var bday = Convert.ToDateTime(yom);

                DateTime today = DateTime.Today;
                int age = today.Year - bday.Year;
                if (bday > today.AddYears(-age)) age--;

                ageList.Add(age);
            }
        }
    }

The error I am getting at runtime is:

Unable to cast object of type 'Microsoft.LightSwitch.Presentation.Framework.NewItemPlaceholderDataContext' to type 'LightSwitchApplication.InsuranceQuotation'.

1

There are 1 best solutions below

4
AudioBubble On

Try this fix

void EditableCustomersGrid_ControlAvailable(object sender, ControlAvailableEventArgs e)
{
     List<int> ageList = new List<int>();
     if (e.Control is DataGrid)
     {
        DataGrid dg = (DataGrid)e.Control;
        IList rows = dg.ItemsSource.ToList();//this line lets you get the datagrid rows in Ilist 
        foreach (DataRowView c in rows )
        {
             var yom = c["mYear"];
             var bday = Convert.ToDateTime(yom);
             DateTime today = DateTime.Today;
             int age = today.Year - bday.Year;
             if (bday > today.AddYears(-age)) age--;
                ageList.Add(age);
        }
    }
}