Following is the sample code to read the data from Database table Student(id,FirstName,LastName) using SQLDATAREADER
and bind it to the GridView .
ExDataReader.aspx
and bind it to the GridView .
ExDataReader.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExDataReader.aspx.cs" Inherits="ExDataReader" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="Student_Id" HeaderText=" ID" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
</Columns>
<RowStyle HorizontalAlign="Center" />
</asp:GridView>
</div>
</form>
</body>
</html>
ExDataReader.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class ExDataReader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection Connobj = new SqlConnection();
Connobj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
Connobj.Open();
// Create a command object
SqlCommand cmdGetStudent = new SqlCommand("select * from student", Connobj);
// Create a data reader object.
SqlDataReader dread;
// Execute the command
dread = cmdGetStudent.ExecuteReader();
GridView1.DataSource = dread;
GridView1.DataBind();
// Close the reader
dread.Close();
// Close the database connection.
Connobj.Close();
}
}
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