Saturday, November 20, 2010

Simple Database Connection using C#

To connect to database using C# is very easy. I am using VS 2008. The database being used is MS SQL Server.
First let me tell the steps involved in connecting to the database 
1. Make a note of the connection string. The information needed are 
         a. Data Source;
         b. Initial Catalog;
2. Once you have this information, do not forget to include SqlClient in the "using" directive. 
3. Initialize SqlConnection by providing the Datasource and Initial catalog information
4. Open the connection. 
5. Read the data using SqlDataReader
6. You can bind the data to a grid view. 
7. Close the connection. 

Now coming to the coding part.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;



namespace DBConnect
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          //You can call the function in the button click event. 
          DBConnect();
        }


         /// <summary>
        /// Method to connect to the DB
        /// </summary>
        /// <returns></returns>
        protected void DBConnect()
        {        
            //Connection String. 
            SqlConnection conn = new SqlConnection("Data Source=Database Source;Initial Catalog=Database;Integrated Security=True");
             SqlDataReader dataReader = null; 
            try
            {
               //Opening the connection.
                conn.Open();
                if (conn != null)
                       string selectString = "Select * from Employer";
                       SqlCommand cmd = conn.CreateCommand();
                       cmd.CommandText = selectString;
                       dataReader = cmd.ExecuteReader();
                       //Checking if the dataReader is empty or not
                       if (dataReader.HasRows)
                      {
                  //Setting the datasource of the grid view to //the SQL Data Reader
                          gridView1.DataSource = dataReader;
                         //Binding it to the grid view
                         gridView1.DataBind();
                      }
            }
            finally
             {
                 //Closing the data reader
                 if (dataReader != null)
                 {
                     dataReader.Close();
                 }
                 conn.Close();
             }
        }
    }
}

There you go. Your database is connected and the values are put into the grid view.

No comments:

Post a Comment