如何更改asp.net中的datagridview列日期格式? [英] how to change datagridview column date format in asp.net?

查看:142
本文介绍了如何更改asp.net中的datagridview列日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这在vb.net datagridview中起作用.Columns[0] .DefaultCellStyle.Format ="yy/mm/dd";
但是在asp.net中没有"DefaultCellStyle",所以我该怎么做.

this works in vb.net datagridview .Columns[0].DefaultCellStyle.Format = "yy/mm/dd";
but in asp.net there is no "DefaultCellStyle" so how do i do this.

推荐答案


您可以在asp:BoundField中使用"DataFormatString"属性来格式化日期字段.这是示例代码

You can use "DataFormatString" property in asp:BoundField to format the date fields. Here is the sample code

<asp:gridview id="GridView1" runat="server" xmlns:asp="#unknown">
    <columns>
        <asp:boundfield datafield="JoinDate" dataformatstring="{0: dd-MM-yyyy hh:mm tt }" />
    </columns>
    </asp:gridview>



您还可以使用源代码通过Gridviews RowDataBound事件更改日期格式.找到适合您的日期的模板控件,然后在此事件中将日期转换为所需的格式.



you can also use the source code to change the date format using Gridviews RowDataBound event. Find the template control for your date and then convert the date to your required format in this event.


Here is the aspx code
<pre lang="HTML">
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server"

        onrowdatabound="GridView1_RowDataBound">
    <Columns>
        <%--<asp:BoundField DataField="JoinDate" DataFormatString="{0: dd-MM-yyyy hh:mm tt }" />--%>
        <asp:TemplateField HeaderText="Joining date">
            <ItemTemplate>
                <asp:Label ID="lblJoinDate" Text='<%#Eval("joindate") %>' runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    </asp:GridView>
</pre>

and this is the code behind in c#
<pre lang="c#">
protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = createDataSource();
        GridView1.DataBind();
    }

    private DataTable createDataSource()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("JoinDate", typeof(DateTime));
        dt.Rows.Add(DateTime.Now);
        return dt;
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblJoinDate = (Label)e.Row.FindControl("lblJoinDate");
            DateTime joindate = Convert.ToDateTime(lblJoinDate.Text);
            lblJoinDate.Text = joindate.ToString("dd-MM-yyyy hh:mm:ss tt");
        }
    }
</pre>

Hope it will help you


这篇关于如何更改asp.net中的datagridview列日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆