Binding GridView from List

Binding GridView from List<T> in ASP.Net

Introduction

I would like to share a way by which we can bind the Asp.net Gridview with a template type List.

Steps

1. Create a class and the defining properties

Sample Code

public class Emp 
{
   
public string EMPNo { get; set; }
   
public string EmpName { get; set; }
}

2. Create a method with the return List of the Emp class

Code

public List<Emp> GetEmpList()

{

    List<Emp> lstEmp = new List<Emp>();

    Emp objEmp = new Emp();

    objEmp.EMPNo = "23";

    objEmp.EmpName = "DEVESH OMAR";

    lstEmp.Add(objEmp);

 

    objEmp = new Emp();

    objEmp.EMPNo = "46";

    objEmp.EmpName = "NIKHIL VATS";

    lstEmp.Add(objEmp);

 

    objEmp = new Emp();

    objEmp.EMPNo = "37";

    objEmp.EmpName = "KUMAR GAURAV";

    lstEmp.Add(objEmp);

 

    objEmp = new Emp();

    objEmp.EMPNo = "36";

    objEmp.EmpName = "RAM PRAKSSH";

    lstEmp.Add(objEmp);

 

    objEmp = new Emp();

    objEmp.EMPNo = "56";

    objEmp.EmpName = "VISHAL";

    lstEmp.Add(objEmp);

 

    objEmp = new Emp();

    objEmp.EMPNo = "40";

    objEmp.EmpName = "POOJA";

    lstEmp.Add(objEmp);

    return lstEmp;

}

A List of the Emp is a collection of objects of the Emp class.

We can create a list of the Emp using List<Emp> lstEmp = new List<Emp>();

Above return list of Emp objects

3. Creation of the ASPX page.

4. Adding a GrivewControl to the ASPX page

<asp:gridview id="EMPGRIDDATA" runat="server" backcolor="White" bordercolor="#E7E7FF"

    borderstyle="None" borderwidth="1px" cellpadding="3" font-names="Calibri" font-size="Larger"

    gridlines="Horizontal">

<AlternatingRowStyle BackColor="#F7F7F7" />

<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />

<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />

<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />

<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />

<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />

<SortedAscendingCellStyle BackColor="#F4F4FD" />

<SortedAscendingHeaderStyle BackColor="#5A4C9D" />

<SortedDescendingCellStyle BackColor="#D8D8F0" />

<SortedDescendingHeaderStyle BackColor="#3E3277" />

</asp:gridview>

5. Binding Gridview control with the List

protected void Page_Load(object sender, EventArgs e)

{

    EMPGRIDDATA.DataSource = new Emp().GetEmpList();

    EMPGRIDDATA.DataBind();

}

6. Preview of Code.

The following screen contains EmpNo and Empname as its headers.


From the given above point, we have created an EmpNo and an Empname as the properties of the Emp class.
Ebook Download
View all
Learn
View all