Monday 4 April 2011

Bind Grid view without using Database Table


How to bind data on grid view without using Database?

Yes possible to bind data on Gridview without  using database. Create one data table, add columns and its values through code and bind it in the grid view.
Refer below code for the example
Client Side
Place grid view inside of form tag
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
 <asp:BoundField HeaderText="Employee No" DataField="Empno" />
 <asp:BoundField HeaderText="Employee Name" DataField="Empname" />
 <asp:BoundField HeaderText="Employee Salary" DataField="Salary" />
</Columns>
</asp:GridView>
Server Side
using System.Data;
using System.Data.SqlClient;

public partial class BindGrid_WithoutDB : System.Web.UI.Page
{
    DataTable dt = new DataTable();
    DataRow dr;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGrid();
        }
    }
    void BindGrid()
    {
        dt.Columns.Add("Empno");
        dt.Columns.Add("Empname");
        dt.Columns.Add("Salary");
        dr = dt.NewRow();
        dr["Empno"] = "101";
        dr["Empname"] = "Ravindran";
        dr["Salary"] = "25000";
        dt.Rows.Add(dr);
        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}

Output:


No comments:

Post a Comment