I have written c# code to call ms access function.
Below is the function call “CallModule
” written in c# .
There is a function called “fReturnRecordset
” in ms access. This function returns Recordset.
From c# we are able to call function successfully. But we are not able to typecast oRrecordSet object to recordset or dataset.
I get following error :
“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)).”
Whenever I try the typasting.(see the commented line in the code i.e //Recordset rs=(Recordset)oRrecordSet;
)
ms access function :
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# code :
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;
}
}
How to do typecasting of the returned object, to recordset or dataset to fill the grid.
Above approach is correct. It needs some more code to iterate through the recordset to fill the data table object.
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.MoveNext();
}
oRecordSet.Close();
oAccess.DoCmd.Quit(AcQuitOption.acQuitSaveNone);
oAccess = null;
return dt;
}
catch (Exception ex)
{
throw;
}
}
User contributions licensed under CC BY-SA 3.0