开发者

How to bind a List<DateTime> to a GridView

I already read Stack Overflow question How to bind a List to a gridview?.

But I need to bind a List<DateTime> to a gridview, but MAINLY I also want be able to access the DateTime value from within a ItemTemplate. How do I do that? When I was working with a DataTable, I used to do it like that:

<%# Eval("SDIndex") %>

How would I开发者_如何学C do it linking it directly to the List<DateTime>?


You may try the following:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Linq" %>
<script type="text/C#" runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        var dates = Enumerable.Range(1, 20).Select(x => new DateTime(2011, 4, x)).ToList();
        grd.DataSource = dates;
        grd.DataBind();
    }
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="Form1" runat="server">
    <asp:GridView ID="grd" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <%# ((DateTime)GetDataItem()).ToString("dd/MM/yyyy") %>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

This should also work:

<%# string.Format("{0:dd/MM/yyyy}", GetDataItem()) %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜