Sunday, February 20, 2011

Accessing database is pretty simple job using C# and ADO

Accessing database is pretty simple job using C# and ADO. In this sample code,
I access an access database Test.mdb, which has a table called "Developer". I display contents of the table in a listbox.

Just add a list box to the form and the following code to the form load. Don't forget to add reference to System.Data and System.Data.OleDb namespaces.






private void Form1_Load(object sender, System.EventArgs e)
{
string strDSN = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\Test.MDB";
string strSQL = "SELECT * FROM Developer" ;


// create Objects of ADOConnection and ADOCommand
OleDbConnection myConn = new OleDbConnection(strDSN);
OleDbDataAdapter myCmd = new OleDbDataAdapter( strSQL, myConn );
myConn.Open();
DataSet dtSet = new DataSet();
myCmd.Fill( dtSet, "Developer" );
DataTable dTable = dtSet.Tables[0];
foreach( DataRow dtRow in dTable.Rows )

{
listBox1.Items.Add( dtRow["Name"].ToString());
listBox1.Items.Add( dtRow["Address"].ToString());
}
}

No comments:

Post a Comment