|
Author: Jenny Nguyen
|
|
How to easily use Enterprise Library for Windorm to access the data from the database. Enterprise Library is really easy to use and help you reduce the amount of coded you need to write to work with the database. 1. If you haven't yet download the latest version of the Enterprise Library then you can download it from Microsoft. At the time of this writing the latest version is version 5.0. 2. Open Visual Studio and create a new Winform project. 3. Add the two references Microsoft.Practices.EnterpriseLibrary.Common and Microsoft.Practices.EnterpriseLibrary.Data to the references folder. Normally the DLLs can be located within C:\Program Files\Microsoft Enterprise Library 4.1 - October 2008\Bin. 4. Add a new Application Configuration (App.config) file. Make sure you have the follow setting in the configuration file. Update the connection string property to the correct database. <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </configSections> <dataConfiguration defaultDatabase="testConn" /> <connectionStrings> <add name="testConn" connectionString="Data Source=AUPERSQLD20;Initial Catalog=testDB;Persist Security Info=True;User ID=testuser;Password=taltm?0" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> 5. Here is how you use it in the code file. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.Practices.EnterpriseLibrary.Data; using Microsoft.Practices.EnterpriseLibrary.Data.Sql; using System.Data.Common;
namespace WinformEnterpriseLibrary { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { Database db = DatabaseFactory.CreateDatabase(); DbCommand dbCommand = db.GetStoredProcCommand("dbo.prPlantsSelect");
// If you need to add in the parameter then here is how you do it. // db.AddInParameter(dbCommand, "RootEntityID", DbType.Int32, cbPlant.GetColumnValue("RootEntityID")); DataTable dt = db.ExecuteDataSet(dbCommand).Tables[0];
comboBox1.ValueMember = "ID"; comboBox1.DisplayMember = "Description"; comboBox1.DataSource = dt; } } }
|