Thursday, April 12, 2012

ADO Example One

The form has a Gridview and a button. Here is the code for the first ADO example. I commented it thoroughly


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//ADO libraries
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //create a connection object for connecting to the database
        //the Data source is the server 
        //the initial catalog is the database
        //integrated security means use your windows account for authentication
        //only works if your windows account has permission in sql Server
        SqlConnection connect = new SqlConnection
            ("Data source=localhost;Initial Catalog=CommunityAssist;integrated Security=true");

        //sql string
        string sql = "Select * from [Service]";

        //the command object passes the sql through the connection
        //to the server
        SqlCommand cmd = new SqlCommand(sql, connect);

        //the data reader reads the data
        //but doesn't retain it
        SqlDataReader reader = null;

        //open the connection
        //most errors will occur here because
        //this is the first time that any of the code
        //is actually executed
        connect.Open(); 
        //execute the reader through the command object
        reader = cmd.ExecuteReader();
        //write the data into the GridView
        GridView1.DataSource = reader;
        //bind the data to the grid
        GridView1.DataBind();
        //get rid of the reader
        reader.Dispose();
        //close the connection
        connect.Close();
    }
}

No comments:

Post a Comment