Linq query has an implicit cast error for DataGridViewRow when option strict is enabled

后端 未结 1 1541
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 16:27

I have a DataGridView that is bound to a list of objects called \"BaseChange\". The BaseChange objects are made up of 4 properties...

  • ChangeType
  • ChangeSta
1条回答
  •  一生所求
    2021-01-24 16:48

    (From _row As DataGridViewRow In dgvChanges.Rows() 
    

    your type of the _row object has to match the single version of the collection type.

    as in:

        'Assumes Option Strict On and Option Implicit On
        Dim _changes = (From _row In dgvChanges.Rows() _            
               Where Convert.ToBoolean(ctype(_row,DataGridViewRow).Cells(NAME_COLUMN_IS_SELECTED).Value) = True _           
    Select DirectCast(ctype(_row,DataGridViewRow).DataBoundItem, BaseChange)).ToList()
    

    Linq sees your Rows() collection as IEnumerable, so your row is an object. Explanation at the bottom goes into more detail.

    Added:

    Adding Option Infer should simplify this.

    See for more details:

    What is the best way to mix VB.NET's Option Strict and the new Option Infer directives?

    and

    http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/e3ec737a-42f8-4767-a190-78390202a991/

    Explanation: I did some more digging as to why it isn't simpler. RowCollection for a DataGridView implements the older IEnumberable interface which returns objects, while newer collection types Implement the Generic IEnumerable(Of T) Interface, which returns the type directly, removing the need for casting.

    See msdn for implemented interfaces.

    0 讨论(0)
提交回复
热议问题