如何将'System .__ ComObject'强制转换为记录集或数据集?

时间:2013-09-23 10:23:30

标签: c# ms-access office-interop oledbcommand oledbdataadapter

我已经编写了c#代码来调用ms访问函数。  下面是用c#编写的函数调用“CallModule”。

在ms访问中有一个名为“fReturnRecordset”的函数。此函数返回Recordset。

从c#我们可以成功调用函数。 但是我们无法将oRrecordSet对象强制转换为记录集或数据集。

我收到以下错误:

“Unable to cast COM object of type 'System.__ComObject' to interface type 'ADODB.Recordset'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00001556-0000-0010-8000-00AA006D2EA4}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).”

每当我尝试打字时(参见代码中的注释行,//Recordset rs=(Recordset)oRrecordSet;

ms访问功能:

Public Function fReturnRecordset() As Recordset
     Dim MyDB As DAO.Database
     Dim MyRS As DAO.Recordset
     Dim strSQL As String
     strSQL = "Select * From Customers Order by ContactName;"
     Set MyDB = CurrentDb
     Set MyRS = MyDB.OpenRecordset(strSQL, dbOpenSnapshot)
     Set fReturnRecordset = MyRS
End Function

c#c​​ode:

public void CallModule()
    {
        try{
        Microsoft.Office.Interop.Access.Application oAccess = new Microsoft.Office.Interop.Access.Application();
        oAccess.Visible = true;
        oAccess.OpenCurrentDatabase(@"Path to accdb", false);
        object oRrecordSet = oAccess.Run("fReturnRecordset");
        //Recordset rs=(Recordset)oRrecordSet;
        oAccess.DoCmd.Quit(AcQuitOption.acQuitSaveNone);
        oAccess = null;
        }
        catch (Exception ex)
        {
            throw;
        }
    }

如何对返回的对象,记录集或数据集进行类型转换以填充网格。

1 个答案:

答案 0 :(得分:1)

以上方法是正确的。它需要一些代码来迭代记录集来填充数据表对象。

public DataTable CallModule()
    {
        try{
        Microsoft.Office.Interop.Access.Application oAccess = new Microsoft.Office.Interop.Access.Application();
        oAccess.Visible = false;
        oAccess.OpenCurrentDatabase(DataBase, false);
        dao.Recordset oRecordSet = oAccess.Run("fReturnRecordset");

        oRecordSet.OpenRecordset();

       //------------------------------------
        DataTable dt = new DataTable();
        dt.Columns.Add("OriginalName");
        dt.Columns.Add("ModifiedName");

        while (!oRecordSet.EOF )
        {
            DataRow dr = dt.NewRow();
            dr["OriginalName"] = Convert.ToString(oRecordSet.Fields[0].Value);
            dr["ModifiedName"] = Convert.ToString(oRecordSet.Fields[1].Value);
            dt.Rows.Add(dr);
        }

        oRecordSet.Close();

        oAccess.DoCmd.Quit(AcQuitOption.acQuitSaveNone);

        oAccess = null;

        return dt;
        }
        catch (Exception ex)
        {
            throw;
        }
    }