Hi steven,
DataBase
CREATE TABLE [Vegetables](
[ID] [int] NULL,
[Name] [varchar](50) NULL,
[PricePerKg] [varchar](50) NULL
) ON [PRIMARY]
HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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="gvVegetables" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="PricePerKg" HeaderText="PricePerKg" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
NameSpace
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
Code
public partial class _Default : System.Web.UI.Page
{
#region event
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(constr))
{
using (SqlCommand sqlCommand = new SqlCommand("SELECT Id, Name, PricePerkg FROM Vegetables", sqlConnection))
{
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
{
using (DataTable dtVegetables = new DataTable())
{
sqlDataAdapter.Fill(dtVegetables);
gvVegetables.DataSource = dtVegetables;
gvVegetables.DataSource = dtVegetables;
gvVegetables.DataBind();
}
}
}
}
}
#endregion
}
Screenshot
