Binding Data From Database To Grid View In ASP.net c#
In this article i will bind sql data table into gridview using asp.net c#. i will use dataset and datatable to fetch the data from database and bind it griview.
Step 1. Create a database name it Login.
Step 2. Create a table in Login database name it Student_Info.
Step 3. Insert Data into sql table (Student_Info).
insert into Student_Info values(1,'Ravi',12,'Delhi',11)
insert into Student_Info values(2,'Alok',14,'Meerut',12)
insert into Student_Info values(3,'Raj',16,'pune',13)
insert into Student_Info values(4,'Mohit',18,'London',14)
insert into Student_Info values(5,'Piyush',20,'India',15)
Step 4. Open visual studio and create a empty Web application name it Binddatagrid.
Step 5. Add a web form in the application (Binddatagrid) name it binddata.
Step 6. Add a gridview control on web form designer side or copy line given below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="binddata.aspx.cs" Inherits="binddata" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvbind" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Sno" HeaderText="Serial no"></asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="Name"></asp:BoundField>
<asp:BoundField DataField="Age" HeaderText="Age" ></asp:BoundField>
<asp:BoundField DataField="Address" HeaderText="Address" ></asp:BoundField>
<asp:BoundField DataField="rollno" HeaderText="Roll Number"></asp:BoundField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Step 7. Add name space in code behind file.
using System.Data;
using System.Data.SqlClient;
Step 7. Add given Asp.net C# code on code behind file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class binddata : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
SqlConnection con= new SqlConnection(@"Server=.;Database=Login; Integrated Security=True;"); // connectio string for connect to database
String patt = "select * from Student_Info ";
SqlCommand cmd = new SqlCommand(patt, con); // sql command for command executaion
SqlDataAdapter da = new SqlDataAdapter(cmd); // dataadapter set of table
dt = new DataTable();
da.Fill(dt); // fill method use to fill data table from set of table
gvbind.DataSource=dt;
gvbind.DataBind(); // Grid bind
}
}
}
Result : Run Application and result will be
0 Comments
Post a Comment