Tuesday, February 14, 2012

Display Sql Server data in Gridview

Displaying Sql Server data in Gridview

Step 1) Install and configure Sqlserver 2005

Step 2)Write following code to your ASP.NET page

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

<!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>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#3366CC"
            BorderStyle="None" BorderWidth="1px" CellPadding="4">
            <RowStyle BackColor="White" ForeColor="#003399" />
            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />

Step 4) Add following code in the code behind of your ASP.NET page
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 sqlserver : System.Web.UI.Page

    SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    SqlDataReader rd;
    public string query;

    protected void connection()
        con.ConnectionString = "server=.\\SQLEXPRESS; integrated security=SSPI; initial catalog=sourav;";
        cmd.Connection = con;

    protected void Page_Load(object sender, EventArgs e)
        //Calling connection function

        cmd.CommandText = "select * from loginfo";
        rd = cmd.ExecuteReader();
        this.GridView1.DataSource = rd;


1 comment:

  1. I have tried this code, same code, but it isn't working on SQL Server 2008. Please guide