无法将类型为“System.Data.DataRow”的对象强制转换为“System.Data.DataRowView”

时间:2013-01-03 16:26:51

标签: c# c#-4.0

我收到了错误:

  

无法将“System.Data.DataRow”类型的对象强制转换为“System.Data.DataRowView”。

    private void addToOrder(DataRowView drv)
    {
        DataRow dr = orderDataTable.NewRow();
        dr["ProductID"] = drv["ProductID"];
        dr["ProductBarcode"] = drv["ProductBarcode"];
        dr["ProductName"] = drv["ProductName"];
        dr["SalePrice"] = drv["SalePrice"];
        dr["SoldQuantity"] = 1;
        dr["NotEditable"] = false;
        try
        {
            orderDataTable.Rows.Add(dr);
        }
        catch (ConstraintException)
        {
            DataRow dr1 = orderDataTable.Rows.Find(drv["ProductID"]);
            dr1["SoldQuantity"] = Convert.ToInt32(dr1["SoldQuantity"]) + 1;
        }
    }
    private void btnAddToOrder_Click(object sender, RoutedEventArgs e)
    {
        // add to order
        if(txtBarcodeAuto.Text.Length >0)
        {
            //get data from sql server database for product details(productID, ProductName,ProductPrice)
            DataTable dscrntProd = prods.SelCrntProd4Sale(crntProdID);
            foreach (DataRowView dr in dscrntProd.Rows)
            {
                addToOrder(dr);
            }
        }
    }

3 个答案:

答案 0 :(得分:2)

由于数据类型不匹配,错误发生在下一行。

foreach (DataRowView dr in dscrntProd.Rows) // as dscrntProd  is DataTable

应该是

foreach (DataRow dr in dscrntProd.Rows)
{
  addToOrder(GetOrderDataRowViewFromDataFow(dr));
}  

您需要撰写GetOrderDataRowViewFromDataRow

答案 1 :(得分:1)

那么,哎呀,不要那么做。试试这个:

private void addToOrder(DataRow drv)
{
    ....
}

foreach (DataRow dr in dscrntProd.Rows)
{
    addToOrder(dr);
}

答案 2 :(得分:0)

DataRow无法转换为DataRowView

foreach(DataRow dr in dscrntProd.Rows)
{
    addToOrder(dr);
}

private void addToOrder(DataRow dr) // change the function argument to DataRow.
    {// Do something.
}

感谢。