user2457518
user2457518

Reputation:

Invalid cast exception - Unable to cast object type 'System.Data.DataRowView' to type 'System.Data.DataRow'

I have the following code

public void ConstructUpdateableInventoryItemsOnThisPage(DataView dv)
{
    //DataRowView dv = null;
    string sTemp = "";

    foreach (DataRow dr in dv)
    {
        if (sTemp.Length > 0)
        {
            sTemp += ",";
            sTemp += dr["inventory_id"];
        }
    }

    //foreach (DataRow dr in dv)
    //{
    //    if (sTemp.Length > 0)
    //        sTemp += ",";
    //    sTemp += dr.ItemArray[Convert.ToInt32("inventory_id")];  //added ItemArray keyword, square brackets and syntax to convert from string to int 10/21/15 Max //

    //}



    mUpdateableInventoryItemsOnThisPage = sTemp;

}

And when I go to execute the code I receive the following error:

Invalid Cast Exception - Unable to cast object type 'System.Data.DataRowView' to type 'System.Data.DataRow'

I know that the issue is somewhere in the foreach statement so just in case I included the original code (commented out) and the changes that I made (not commented out). I am not sure what is causing this could someone point me in the right direction syntactically

Oh by the way this was converted from visual basic if that helps any

Upvotes: 0

Views: 2838

Answers (3)

Salah Akbari
Salah Akbari

Reputation: 39946

The DataRowView is not convertible to DataRow. You can use DataRowView instead of DataRow in foreach. Like this:

foreach (DataRowView dr in dv)
{
     if (sTemp.Length > 0)
     {
          sTemp += ",";
          sTemp += dr.Row["inventory_id"];
     }
}

Or as a better solution by LINQ:

foreach (DataRowView dr in dv.Cast<DataRowView>().Where(dr => sTemp.Length > 0))
{
    sTemp += ",";
    sTemp += dr.Row["inventory_id"];
}

Upvotes: 0

Habib
Habib

Reputation: 223187

You can do:

foreach(DataRowView dr in dv)

and that should fix the issue, The items in the DataView are DataRowView and not DataRow, and since foreach does a silent explicit conversion, you don't see an error at compile time. (More here)

You can also get the required string using String.Join like:

sTemp = String.Join(",", 
                dv.OfType<DataRowView>().Select(dr => 
                                                Convert.ToString(dr["inventory_id"])));

if you want to have , in front of your string then you can use concatenation before string.Join

Upvotes: 1

Nick Kuznia
Nick Kuznia

Reputation: 1768

DataView isn't an enumerable of type DataRow. It's not an array or list of rows. It has a single row accessible with the Row property dv.Row.

You can climb up the hierarchy and back down the the rows: dv.Table.Rows

https://msdn.microsoft.com/en-us/library/system.data.datarowview.dataview(v=vs.110).aspx

Upvotes: 0

Related Questions