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


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

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


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();

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



            GridView1.DataSource = ds.Tables[0];

    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