GridView using LINQ and Convert datetime to shortdate in LINQ.


Step 1. Create Default.aspx page like

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

<!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" AutoGenerateColumns="False">
            <Columns>
                <asp:HyperLinkField DataNavigateUrlFormatString="~/Default2.aspx?id=mydate"
                    DataTextField="mydate" HeaderText="Date" DataNavigateUrlFields="mydate" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</
html>

Step 2: Create test.dbml file for LINQ .

Step 3: Create Default2.aspx for navigate by Default1.aspx like.

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

<!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 style="background-color:Blue">
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</
html>

Step 4: write a code in your Default.aspx.cs file like

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindGridview();
    }

    private void BindGridview()
    {
        using(testDataContext db = new testDataContext())
        {                        
            //This LINQ code create query like.
            var info = from p in db.testdatas
                       select new {
                           mydate = p.dateofbirth.ToShortDateString() // ToShortDateString() convert the longdate to shortdate.
                       };

            /*                         
             *   SELECT [t0].[dateofbirth]
             *  FROM [dbo].[testdata] AS [t0]              
             */

            if ((info != null) && (info.Count() > 0))
            {
                GridView1.DataSource = info;
                GridView1.DataBind();
            }
        }
    }
}

Up Next
    Ebook Download
    View all
    Learn
    View all