I am back with an important idea and to begin I want to describe the situation. Imagine that you have developed an application using a Microsoft Access database and you have deployed it. What if you change your mind about your database, instead of Access you would like to use a SQL Server database. Wow! Well don't panic, the simple solution is to use the class "DbProviderFactory" from the namespace "System.Data.Common", so instead of fixing your provider you specify which provider you want to use at runtime; that's wonderful.
The code is the following:
- 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 System.Data.Common;
- namespace DDbProviderFactory
- {
- public partial class Form1 : Form
- {
-
-
- public DataSet loadData(string Myprovider, string conStr)
- {
- DbProviderFactory connecteur;
- DbConnection conx;
-
- DataSet ds = new DataSet();
- connecteur = DbProviderFactories.GetFactory(Myprovider);
-
- conx = connecteur.CreateConnection();
- conx.ConnectionString = conStr;
- DbCommand command = connecteur.CreateCommand();
- DbDataAdapter adap = connecteur.CreateDataAdapter();
- command.CommandText = "select * from student";
- command.Connection = conx;
- adap.SelectCommand = command;
- adap.Fill(ds, "student");
- return ds;
- }
- public Form1()
- {
- InitializeComponent();
- txconnection.Items.Add(@"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=" + Application.StartupPath);
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- DataSet ds = new DataSet();
- txprovider.SelectedIndex = 0;
- txconnection.SelectedIndex = 0;
- ds = loadData(txprovider.Text, txconnection.Text);
- dataGridView1.DataSource = ds.Tables["student"];
- }
- private void txprovider_SelectedIndexChanged(object sender, EventArgs e)
- {
- txconnection.SelectedIndex = txprovider.SelectedIndex;
- DataSet ds = new DataSet();
- ds = loadData(txprovider.Text, txconnection.Text);
- dataGridView1.DataSource = ds.Tables["student"];
- }
- }
- }
The UI
So as you can see the same code works with two different databases but with one condition, the database structure is the same, be sure of that.
The source will be included, try to look much more to the "loadData()" method the secret lies there.
I was in front my computer for two hours just to make that look easy, I hope you find it like that, see you soon and try to leave a comment.