Menu

 

Sunday, July 18, 2010

Acessing Data and Other Application

VBA Code :-

Sub UsingDAOWithWord()
Dim docNew As Document
Dim dbNorthwind As DAO.Database
Dim rdShippers As Recordset
Dim intRecords As Integer

Set docNew = Documents.Add
Set dbNorthwind = OpenDatabase _
(Name:="C:\Program Files\Microsoft Office\Office11\" _
& "Samples\Northwind.mdb")
Set rdShippers = dbNorthwind.OpenRecordset(Name:="Shippers")
For intRecords = 0 To rdShippers.RecordCount - 1
docNew.Content.InsertAfter Text:=rdShippers.Fields(1).Value
rdShippers.MoveNext
docNew.Content.InsertParagraphAfter
Next intRecords
rdShippers.Close
dbNorthwind.Close
End Sub

C# Code :-

public void UsingDAOWithWord()
{
///Download Northwind from
///http://www.microsoft.com/downloads/en/confirmation.aspx?familyId=c6661372-8dbe-422b-8676-c632d66c529c&displayLang=en
///if donot have

string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=G:\\Database\\Nwind.mdb";
DataSet myDataSet = new DataSet();
OleDbConnection myAccessConn = null;
string strAccessSelect = "select * from Shippers";
Word.Range rngFirstParagraph;

rngFirstParagraph = ThisApplication.ActiveDocument.Paragraphs[1].Range;
try
{
myAccessConn = new OleDbConnection(strAccessConn);
}
catch (Exception ex)
{

rngFirstParagraph.InsertAfter(String.Format( "Error: Failed to create a database connection. \n{0}" , ex.Message));
return;
}


try
{

OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect, myAccessConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);

myAccessConn.Open();
myDataAdapter.Fill(myDataSet, "Shippers");

}
catch (Exception ex)
{
rngFirstParagraph.InsertAfter(String.Format("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message));
return;
}
finally
{
myAccessConn.Close();
}

DataRowCollection dra = myDataSet.Tables["Shippers"].Rows;
foreach (DataRow dr in dra)
{
// Print the CategoryID as a subscript, then the CategoryName:
rngFirstParagraph.InsertAfter(String.Format("ShippersValue[{0}] is {1}", dr[0], dr[1]));
rngFirstParagraph.InsertParagraphAfter();
}



}

No comments:

Post a Comment