Skip to main content

System.InvalidCastException: Unable to cast object of type 'DevExpress.Data.Async.Helpers.ReadonlyThreadSafeProxyForObjectFromAnotherThread'

  • 2 minutes to read

When you try to cast an object of one type to another, you may see the following exception in the browser console:

Error: System.InvalidCastException: Unable to cast object of type ‘DevExpress.Data.Async.Helpers.ReadonlyThreadSafeProxyForObjectFromAnotherThread’ to type ‘X’.

This error occurs if you use an instant feedback data source. If a data source’s AreSourceRowsThreadSafe option is set to false (the default value), you cannot cast a data item and use the {DataItem.FieldName} notation. Call the GetDataItemValue(Object, String) method to obtain the data item’s field value. Note that this method does not provide access to the data source object and you cannot handle events or call methods related to the object.

The following example gets the value of the selected item:

<DxGrid Data="InstantFeedbackSource"
        AllowSelectRowByClick="true"
        SelectionMode="GridSelectionMode.Single"
        @bind-SelectedDataItem="@SelectedDataItem"
        KeyFieldName="ProductId"
        @ref="MyGrid">
    <Columns>
        <DxGridSelectionColumn />
        <DxGridDataColumn FieldName="ProductName" />
        <DxGridDataColumn FieldName="UnitPrice" />
    </Columns>
</DxGrid>

@* ... *@
@code {
    EntityInstantFeedbackSource InstantFeedbackSource { get; set; }
    NorthwindContext Northwind { get; set; }
    object SelectedDataItem { get; set; }
    IGrid MyGrid { get; set; }
    string SelectedProductInfo { get; set; }

    protected override void OnInitialized() {
        Northwind = NorthwindContextFactory.CreateDbContext();
        InstantFeedbackSource = new EntityInstantFeedbackSource(e => {
            e.KeyExpression = "ProductId";
            e.QueryableSource = Northwind.Products;
        });
    }

    void OnGetSelectedProductName() {
        SelectedProductInfo = (string)MyGrid.GetDataItemValue(SelectedDataItem, "ProductName");
    }
    @* ... *@
}