Monday, March 26, 2012

Binding list to grid view


Below sample explains how to bind a collections lost object to a grid view.

public class MyClass1
{
    public string Name
    { get; set; }
}

public class MyClass2
{
    public string Name
    { get; set; }

    public MyClass1 Class1
    { get; set; }
}

Collection (List) of MyClass2, will have the set of objects which can be binded to the grid.
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected bool ShowGrid = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGrid();
            ShowGrid = true;
        }
    }

    private void BindGrid()
    {
        List<MyClass2> obj = new List<MyClass2>();
        obj.Add(new MyClass2() { Name = "Class2_1", Class1 = new MyClass1() { Name = "Class1_1" } });
        obj.Add(new MyClass2() { Name = "<br/><br/><br/>hi", Class1 = new MyClass1() { Name = "<br/><br/><br/>hi" } });
        obj.Add(new MyClass2() { Name = "Class2_2", Class1 = null});
        grd.DataSource = obj;
        grd.DataBind();
    }
}

public class MyClass1
{
    public string Name
    { get; set; }
}

public class MyClass2
{
    public string Name
    { get; set; }

    public MyClass1 Class1
    { get; set; }
}


ASPX Page :
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>
    <%@ Import Namespace="Microsoft.Security.Application" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <%if (ShowGrid)
      {%>
    <asp:GridView ID="grd" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField HeaderText="Class1 Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%#(null==Eval("Class1"))?" is null " : Eval("Class1.Name").ToString()%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Class2 Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# AntiXss.HtmlEncode(Eval("Name").ToString()) %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            No Data
        </EmptyDataTemplate>
    </asp:GridView>
    <%} %>
</asp:Content>


No comments: