Thursday, January 24, 2019

How to create access database using c# programmatically


In this article i have explain how create access database using c# code

Step 1 : Create a new window application project .

 
new project are created in visual studio.

Step 2: Add The Reference using ms access database


Required reference are add to your project

Step 3: Add button control on your form control


Step 4 : Add the following code your cs file

using System;
using System.Windows.Forms;
namespace myApplication
{
    public partial class Database : Form
    {
        public Database()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (CreateNewAccessDatabase("mynewDatabase.accdb"))
            {
                MessageBox.Show("Your Access Database Successfully Created !");
            }
        }
        public bool CreateNewAccessDatabase(string fileName)
        {
            bool result = false;
            ADOX.Catalog cat = new ADOX.Catalog();
            ADOX.Table table = new ADOX.Table();
            //Create the table and it's fields.
            table.Name = "tblMyTable";
            table.Columns.Append("Name");
            table.Columns.Append("Age");
           
            try
            {
                cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5");
                cat.Tables.Append(table);
                //Now Close the database
                ADODB.Connection con = cat.ActiveConnection as ADODB.Connection;
                if (con != null)
                    con.Close();
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            cat = null;
            return result;
        }
    }
}

Now run the application and click on the create database button your database created 

The Database File Loaction 


Access database 



No comments:

Post a Comment

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...