Sunday, June 15, 2014

How to bind the Asp.Net grid with selected data using Lambda Expressions

Write the bellow code for and execute

In Design Side

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LinqAndLambdaExpressions.aspx.cs"
    Inherits="SampleTestingCodes.LinqAndLambdaExpressions" %>

<!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>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="UserId" />
                <asp:BoundField DataField="UserName" />
                <asp:BoundField DataField="Education" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>


In .cs Side
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace SampleTestingCodes
{
    public partial class LinqAndLambdaExpressions : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("UserId", typeof(int));
            dt.Columns.Add("UserName", typeof(string));
            dt.Columns.Add("Education", typeof(string));
            dt.Rows.Add(1, "Lokesh", "B.Tech");
            dt.Rows.Add(2, "Vijay", "Msc");
            dt.Rows.Add(3, "Balaji", "MS");
            dt.Rows.Add(4, "Charan", "B.Tech");
            dt.Rows.Add(5, "Durga", "MD");
            dt.Rows.Add(6, "Shiva", "B.Tech");
            dt.Rows.Add(7, "Venkat", "CA");

            var dss = dt.AsEnumerable().Where(s => s.Field<int>("UserId") >= 1);

            GridView1.DataSource = dss.CopyToDataTable();
            GridView1.DataBind();
        }
    }
}


No comments:

Post a Comment