In this article I’m
going to explain how to bind data to GridView in ASP.NET using C#.
What
is Gridview ?
Gridview control
displays
the values of a data source in a table where each column represents a field and
each row represents a record. The GridView control enables you to select,
sort, and edit these items.
Here I’ll show you how to bind data to
Gridview from
data source.
I have used
Northwind database to bind Product details to GridView. Here you can
download Northwind database
http://northwinddatabase.codeplex.com/releases/view/71634
Table
design:
Column Name
|
Data Type
|
ProductID
|
int
|
ProductName
|
varchar(100)
|
QuantityPerUnit
|
float
|
UnitPrice
|
float
|
UnitsInStock
|
int
|
UnitsOnOrder
|
int
|
Designer
source code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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="gvProduct" runat="server" Width="600px" AutoGenerateColumns="false">
<HeaderStyle BackColor="#3E3E3E"
Font-Bold="True"
Font-Names="cambria"
ForeColor="White"
Height="25px"
/>
<RowStyle Font-Names="Calibri"
Height="25px"
/>
<Columns >
<asp:BoundField DataField="ProductID"
HeaderText="Product
ID" />
<asp:BoundField DataField="ProductName"
HeaderText="Product
Name" />
<asp:BoundField DataField="QuantityPerUnit"
HeaderText="Quantity
Per Unit" />
<asp:BoundField DataField="UnitPrice"
HeaderText="Unit
Price" />
<asp:BoundField DataField="UnitsInStock"
HeaderText="Units
In Stock" />
<asp:BoundField DataField="UnitsOnOrder"
HeaderText="Units
On Order" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
C#-code:
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 _Default : System.Web.UI.Page
{
SqlConnection
conn = new SqlConnection("Data Source=SPIDER;Initial
Catalog=Northwind;Integrated Security=True");
protected
void Page_Load(object
sender, EventArgs e)
{
if (!IsPostBack)
{
BindList();
}
}
private void
BindList()
{
DataSet ds = new DataSet();
string cmdstr = "select
ProductID, ProductName, QuantityPerUnit, UnitPrice,
UnitsInStock, UnitsOnOrder from Products";
SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conn);
adp.Fill(ds);
gvProduct.DataSource =
ds;
gvProduct.DataBind();
}
}