How to Bind Datatable to Gridview in ASP.NET
This article will explain you about binding a data table to gridview in ASP.NET.......
Lets us assume we have got a Default.aspx web form and a Gridview called gvProducts in that web form.
Here is a sample code in code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindProducts();
}
}
private void BindProducts()
{
DataTable tblProducts = new DataTable();
tblProducts.Columns.Add("Id", System.Type.GetType("System.Int32"));
tblProducts.Columns.Add("Name", System.Type.GetType("System.String"));
tblProducts.Columns.Add("Price", System.Type.GetType("System.Decimal"));
tblProducts.Columns.Add("Published", System.Type.GetType("System.Boolean"));
DataRow dr = tblProducts.NewRow();
dr["Id"] = "100";
dr["Name"] = "Apple";
dr["Price"] = "12.36";
dr["Published"] = "true";
tblProducts.Rows.Add(dr);
DataRow dr = tblProducts.NewRow();
dr["Id"] = "101";
dr["Name"] = "Orange";
dr["Price"] = "10.00";
dr["Published"] = "false";
tblProducts.Rows.Add(dr);
DataRow dr = tblProducts.NewRow();
dr["Id"] = "102";
dr["Name"] = "Banana";
dr["Price"] = "15.34";
dr["Published"] = "true";
tblProducts.Rows.Add(dr);
gvProducts.DataSource = tblProducts;
gvProducts.DataBind();
}
}
No comments:
Post a Comment