【问题标题】:asp.net formatting dateTime in gridview在gridview中的asp.net格式化日期时间
【发布时间】:2009-05-07 02:57:23
【问题描述】:

我正在从我称为“会话”的数据库中的一个表中动态绑定一个网格视图。我使用类似这样的 linq 查询从方法中获取信息:

var s = from sessions in datacontext.Sessions
                    where sessions.test == id
                    orderby sessions.ID ascending
                    select sessions;
gridView.DataSource = qsessions;
gridView.DataBind();

Sessions 包含一个 dateTime 字段,我想将其最小化以仅显示日期(月/日/年)。根据我通过谷歌搜索阅读的内容,解决方案是使用以下内容在 gridview 的 aspx 标记中指定格式:

<asp:TextBox ID="txtDate" runat="server" Text='<%# Eval("dateTime", "{0:MM/dd/yyyy}") %>'></asp:TextBox>

它似乎不起作用,仍然显示日期之后的时间。有什么我想念的吗?非常感谢帮助!

【问题讨论】:

    标签: asp.net gridview


    【解决方案1】:

    试试:

    <asp:TextBox ID="txtDate" runat="server" Text='<%# Convert.ToDateTime(Eval("dateTime")).ToString("d") %>'></asp:TextBox>
    

    查看这个有用的网站了解更多格式选项:

    http://www.mikesdotnetting.com/Article.aspx?ArticleID=23

    【讨论】:

    • 谢谢大家。这是第一次尝试。没有尝试过其他的,所以他们可能也可以工作。我很感激!
    • Text=''
    【解决方案2】:

    为网格中的 TextBox 实现 OnDataBinding 事件。

    <asp:TextBox ID="txtDate" runat="server" OnDataBinding="txtDate_DataBinding">
    </TextBox>
    

    然后在你的代码后面实现 OnDataBinding 事件:

    protected void txtDate_OnDataBinding(object sender, System.EventArgs e)
    {
        TextBox txt = (TextBox)(sender);
        txt.Text = (DateTime)(Eval("YourDateField")).ToString("MM/dd/yyyy");
    }
    

    我更喜欢在代码隐藏中包含所有代码,而在 aspx 页面中没有任何内容,但您也可以将其嵌入其中。这是一个线程的链接,我在其中描述了为什么我更喜欢在代码隐藏中这样做:

    OnDataBinding vs Inline: pros, cons and overhead

    【讨论】:

      【解决方案3】:

      ASP gridview 本身支持日期格式,试试添加

      DataFormatString="{0:dd-MM-yyyy}"
      

      【讨论】:

        【解决方案4】:

        Gridview 通过 DataFormatString 支持日期格式。例如-

        <asp:BoundField DataField="Date" HeaderText="Visit date" DataFormatString="{0:dd-MMM-yyyy}" >                               
                                    </asp:BoundField> 
        

        它看起来像这样-

        访问日期
        2013 年 10 月 15 日
        2013 年 10 月 12 日
        2013 年 10 月 11 日

        【讨论】:

          【解决方案5】:
          <asp:Label ID="lblDateBudget" runat="server" Text='<%# Eval("DateBudget", "{0:MM/d/yyyy}")%>'></asp:Label>
          

          您好朋友,这是您上面定义的问题的另一种解决方案。您只需将数据类型设置为 date 而不是 datetime 并尝试以这种方式访问​​。我希望这对你有帮助。

          【讨论】:

            【解决方案6】:

            我认为您的日期时间变量被评估为字符串。尝试将其转换为 DateTime。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-07-01
              • 1970-01-01
              • 2017-06-20
              • 2014-03-19
              • 1970-01-01
              • 2018-09-28
              • 1970-01-01
              相关资源
              最近更新 更多