Home > Net >  Datagrid error when casting to model only when isReadOnly is false?
Datagrid error when casting to model only when isReadOnly is false?

Time:04-17

I have Datagrid and I want to cast the data from each row to a specific model. the casting code is

        private List<SearchAndReplaceModel> getSelectedWordes()
        {
           DGKeywords.UnselectAllCells();
           var repo = new SearchAndReplaceRepository();
          List<SearchAndReplaceModel> selectedWordes = new List<SearchAndReplaceModel>();
           List<SearchAndReplaceModel> dataFromGrid=DGKeywords.Items.Cast<SearchAndReplaceModel>().ToList();
           if (dataFromGrid != null)
            for (int i = 0; i < dataFromGrid.Count; i  )
            {
                selectedWordes.Add ( dataFromGrid[i]);
            }
           return selectedWordes;
        }

the stranger thing is that the code is working perfectly when the property of Datagrid isReadOnly=true but there is exception when I change it to isReadOnly=false

the exception :

Exception thrown: 'System.InvalidCastException' in System.Core.dll An exception of type 'System.InvalidCastException' occurred in System.Core.dll but was not handled in user code Unable to cast object of type 'MS.Internal.NamedObject'

CodePudding user response:

use .OfType() extension method instead of .Cast():

private List<SearchAndReplaceModel> getSelectedWordes()
{
   DGKeywords.UnselectAllCells();
   return DGKeywords.Items.OfType<SearchAndReplaceModel>().ToList();
}

or it maybe simpler to iterate DGKeywords.ItemsSource (depending on how DataGrid is filled with data)

  • Related