How to bind Gridview using Linq and access the value of gridview cell

In this post, I am going to show how to read the value of the GridView cell when the DataSource is anonymous type.

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

<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
</asp:GridView>
</form>
</body>
</html>
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 Default3 : System.Web.UI.Page
{
  /// <summary>
  /// Generic function for coverting object type to Desired type
  /// http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="obj"></param>
  /// <param name="type"></param>
  /// <returns></returns>
  T Cast<T>(object obj, T type)
  {

      return (T)obj;
  }
  /// <summary>
  /// Function return collection of Product and category table as anonymous type
  /// </summary>
  /// <returns></returns>
  private object ProductCategory()
  {
      var query = from p in new Product().GetProducts()
                  join c in new Category().Categories()
                  on p.CategoryId equals c.CategoryId
                  select new
                  {
                      ProductName = p.ProductName,
                      UnitPrice = p.UnitPrice,
                  };
      return query;
  }
  protected void Page_Load(object sender, EventArgs e)
  {

      if (!IsPostBack)
      {
          BindGridView();
      }
  }

  private void BindGridView()
  {
      GridView1.DataSource = ProductCategory();
      GridView1.DataBind();
  }

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
          // This line will get the reference to the underlying row
          object objItem = e.Row.DataItem;
          //this is the hack 
          // This call to 'Cast' method converts first parameter (object) to the
          // same type as the type of second parameter - which is in this case 
          // anonymous type with 'ProductName' and 'UnitPrice' properties

          var _row = Cast(objItem, new { ProductName = "", UnitPrice = ((decimal?)0.0m) });
          if (_row != null)
          {
              // get the field value which you want to compare and
              // convert to the corresponding data type
              decimal? _field = _row.UnitPrice;
              if (_field.Value > 12)
                  e.Row.BackColor = System.Drawing.Color.Green;
              else
                  e.Row.BackColor = System.Drawing.Color.Red;
          }
      }
  }
}

public class Product
{
  public int ProductId { get; set; }
  public string ProductName { get; set; }
  public int CategoryId { get; set; }
  public decimal? UnitPrice { get; set; }

  public List<Product> GetProducts()
  {
      List<Product> products = new List<Product>();
      products.Add(new Product { ProductId = 1, CategoryId = 1, ProductName = "P001", UnitPrice = 12.00m });
      products.Add(new Product { ProductId = 2, CategoryId = 2, ProductName = "P002", UnitPrice = 12.00m });
      products.Add(new Product { ProductId = 3, CategoryId = 1, ProductName = "P003", UnitPrice = 12.45m });
      products.Add(new Product { ProductId = 4, CategoryId = 3, ProductName = "P004", UnitPrice = 11.00m });
      products.Add(new Product { ProductId = 5, CategoryId = 3, ProductName = "P005", UnitPrice = 2.00m });
      products.Add(new Product { ProductId = 6, CategoryId = 3, ProductName = "P006", UnitPrice = 112.00m });
      products.Add(new Product { ProductId = 7, CategoryId = 1, ProductName = "P007", UnitPrice = 122.00m });
      products.Add(new Product { ProductId = 8, CategoryId = 2, ProductName = "P008", UnitPrice = 121.00m });
      products.Add(new Product { ProductId = 9, CategoryId = 1, ProductName = "P009", UnitPrice = 120.00m });

      return products;
  }


}
public class Category
{
  public int CategoryId { get; set; }
  public string CategoryName { get; set; }
  public List<Category> Categories()
  {
      List<Category> list = new List<Category>()
      {
          new Category{ CategoryId=1,CategoryName="C001"},
          new Category{ CategoryId=2,CategoryName="C002"},
          new Category{ CategoryId=3,CategoryName="C003"},
          new Category{ CategoryId=4,CategoryName="C004"},
      };
      return list;

  }

}

Post a Comment

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

Previous Post Next Post

Blog ads

CodeGuru