Monday, August 19, 2013

How to application interacting with a data base using ADO.Net

Step 1)Open Vs2010 File-New-Project ,Web ASP.NET Web Application (Change the project name AdoDotNetExample)



Step2)Than click  OK Button( If you click OK button than project add in solution Explorer )

Step 3)Right click on project(solution Explorer)


Step 4) Web-Web Form (DatabaseConnection.aspx)


Step 5)Know switch to design page :-
Take button and GridView1 from toolbox 


Step 6)I am use here Button click event :-
so double click the button below window u see


Know add Namespace (using System.Data.SqlClient; or  using System.Data;using System.Configuration;)
The full code are as below:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

namespace AdoDotNetExample
{
    public partial class DatabaseConnection : System.Web.UI.Page
    {
        string strsqlcon = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
           
            // 1. Instantiate the connection
            SqlConnection con = new SqlConnection(strsqlcon);
            SqlDataReader rdr = null;
            try
            {
                // 2. Open the connection
                con.Open();
                // 3. Pass the connection to a command object
                SqlCommand cmd=new SqlCommand("Select * from State ",con);

                //
                // 4. Use the connection
                //

                // get query results
                rdr = cmd.ExecuteReader();
                // print the CustomerID of each record
                while (rdr.Read())
                {
                  
                   
                    GridView1.DataSource = rdr;
                    GridView1.DataBind();
                }

            }
            finally
            {
                // close the reader
                if (rdr != null)
                {
                    rdr.Close();
                }
                // 5. Close the connection
                if (con != null)
                {
                    con.Close();
                }
            }
        }
    }
}

 Run you project press F5

if every thing you done right way the output are as below:-




Thank you ,

Please visit and comment

Arjun Walmiki

No comments:

Post a Comment