Bind GridView To Generics List in ASP.NET

In most projects, I used DataSet to bind the GridView.C# Introduced Generics in C#, which is safe and performant. In this blog post, I will show you how to bind GrdiView to a Generic list.

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="GenericsBindGridview.aspx.cs"
 Inherits="GenericsBindGridview" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
     <div>
         <asp:GridView ID="GridView1" runat="server"
DataSourceID="ObjectDataSource1" BorderColor="#CC9966"
             BorderStyle="None" BorderWidth="1px" BackColor="White"
CellPadding="4">
             <HeaderStyle ForeColor="#FFFFCC" BackColor="#990000" Font-Italic="False"
Font-Bold="True">
             </HeaderStyle>
         </asp:GridView>
         <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="OrderSystem"
             SelectMethod="GetOrders"></asp:ObjectDataSource>
     </div>
 </form>
</body>
</html>

Ordersytem.cs

using System;
using System.Collections.Generic;

public class Order
{
   private int _orderId;
   private string _productName;

   public Order(int orderId, string productName)
   {
       _orderId = orderId;
       _productName = productName;
   }

   public string ProductName
   {
       get
       {
           return _productName;
       }
   }

   public int OrderId
   {
       get
       {
           return _orderId;
       }
   }
}

public class OrderSystem
{
   public List<Order> GetOrders()
   {
       List<Order> orders = new List<Order>();
       orders.Add(new Order(123, "Dell"));
       orders.Add(new Order(345, "Toshiba"));
       orders.Add(new Order(567, "Compaq"));
       return orders;
   }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru