Display DateTime column value from another Table in ASP.Net GridView using Entity Framework

Rezu2215
 
on Jun 13, 2019 11:52 PM
1469 Views

I have a gridview and i want to display a dateTime column from another table in this gridview. Please help with that.
Thanks in advance.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
pandeyism
 
on Jun 14, 2019 04:56 AM
on Jun 14, 2019 04:57 AM

Hi Rezu2215,

Refer below sample.

Database

For this sample I have used of NorthWind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="OrderID" HeaderText="Id" />
        <asp:BoundField DataField="ShipName" HeaderText="Ship Name" />
        <asp:BoundField DataField="Freight" HeaderText="Freight" />
        <asp:TemplateField HeaderText="Date Of Birth">
            <ItemTemplate>
                <asp:Label ID="Label1" Text='<%# GetBirthDate(Convert.ToInt32(Eval("EmployeeID")))%>'
                    runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Namespaces

C#

using NorthwindModel;

VB.Net

Imports NorthwindModel

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    NorthwindEntities entity = new NorthwindEntities();
    gvProducts.DataSource = entity.Orders.Take(10).ToList();
    gvProducts.DataBind();
}

public string GetBirthDate(int employeeID)
{
    NorthwindEntities entity = new NorthwindEntities();
    return entity.Employees.Where(x => x.EmployeeID == employeeID).Select(x => x.BirthDate).FirstOrDefault().ToString();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim entity As NorthwindEntities = New NorthwindEntities()
    gvProducts.DataSource = entity.Orders.Take(10).ToList()
    gvProducts.DataBind()
End Sub

Public Function GetBirthDate(ByVal employeeID As Integer) As String
    Dim entity As NorthwindEntities = New NorthwindEntities()
    Return entity.Employees.Where(Function(x) x.EmployeeID = employeeID).[Select](Function(x) x.BirthDate).FirstOrDefault().ToString()
End Function

Screenshot