May 26, 2011

Code Sample to Read Data From Database Using SqlDataAdapter and DataSet Object

Following is the sample code to read the data from Database table Student(id,FirstName,LastName)
and bind it to the GridView with paging implementation


Example10.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Example10.aspx.cs" Inherits="Example10" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True"  PageSize ="2" OnPageIndexChanging="PageChange" >
        </asp:GridView>
        <asp:Button ID="btnAddRow" runat="server" Text="AddRow" OnClick="btnAddRow_Click" />&nbsp;
    </div>
    </div>
    </form>
</body>
</html>

Example10.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient ;


public partial class Example10 : System.Web.UI.Page
{
    SqlConnection connObj = new SqlConnection();
    DataSet ds = new DataSet();
    SqlDataAdapter objAdapter;
    protected void Page_Load(object sender, EventArgs e)
    {
            connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
            connObj.Open();




            SqlCommand objCommand = new SqlCommand("Select * from Country", connObj);
            objAdapter = new SqlDataAdapter(objCommand);


            objAdapter.Fill(ds);


            connObj.Close();


            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
           
    }
   


    public void PageChange(object sender, GridViewPageEventArgs e)
    {


        GridView1.PageIndex = e.NewPageIndex;
    }


    //private void Page_Error(object sender, System.EventArgs e)
    //{
    //    // Get the error.
    //    Exception ex = Server.GetLastError();
    //    Response.Write(ex.Message);




    //    //log Exception
    //    Trace.Warn("Error", "This is the exception Occured",ex);
    //    Trace.Write("Some Error Occured");


    //    // Store the message.
    //    Session["Error"] = ex.Message;


    //    // Clear the error.
    //    Server.ClearError();


    //    // Redisplay this page.
    //    //Response.Redirect("Example10.aspx");
    //}




}



Below is the DotNetTrainingConnectionString in Web.config File

<add name="DotNetTrainingConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=DotNetTraining;Integrated Security=True"
   providerName="System.Data.SqlClient" />


No comments:

Post a Comment