【问题标题】:how to change the format of datetime column when it is bound dynamically in gridview在gridview中动态绑定时如何更改日期时间列的格式
【发布时间】:2011-06-26 04:18:54
【问题描述】:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DateTime dt,dt1;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            dt = Convert.ToDateTime(e.Row.Cells[4].Text);
            e.Row.Cells[4].Text = dt.Month.ToString() + "/" + dt.Day.ToString() + "/" + dt.Year.ToString();
            dt1 = Convert.ToDateTime(e.Row.Cells[5].Text);
            e.Row.Cells[5].Text = dt1.Month.ToString() + "/" + dt1.Day.ToString() + "/" + dt1.Year.ToString();
        }

    }

这是我的代码,索引为 5 的列是日期时间,问题是它可以为 NULL,所以当它为 NULL 时会出现以下错误

“字符串未被识别为有效的日期时间”

任何解决方案请帮忙??!

谢谢你!

【问题讨论】:

    标签: asp.net sql gridview


    【解决方案1】:

    尝试改用DateTime.TryParse,并且仅当它返回 true 时才运行其余代码

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DateTime dt,dt1;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                bool success = DateTime.TryParse(e.Row.Cells[4].Text, dt);
    
                if(success)
                {
                    e.Row.Cells[4].Text = dt.Month.ToString() + "/" + dt.Day.ToString() + "/" + dt.Year.ToString();
                    dt1 = Convert.ToDateTime(e.Row.Cells[5].Text);
                    e.Row.Cells[5].Text = dt1.Month.ToString() + "/" + dt1.Day.ToString() + "/" + dt1.Year.ToString();
                }
        }
    }
    

    【讨论】:

    • 另外根据 MSDN 文档调用 Convert.ToDateTime(null) 将返回 DateTime.Min 所以我不知道你是如何得到一个空异常
    • 错误 2 'System.DateTime.TryParse(string, out System.DateTime)' 的最佳重载方法匹配有一些无效参数 C:\Users\user\Documents\Visual Studio 2010\WebSites\ InventoryLastec\SearchResult.aspx.cs 29 28 C:\...\InventoryLastec\ 它显示这个错误
    • 上面写着  当我的日期时间列为空时,无法转换为日期时间
    【解决方案2】:

    您尝试过简单的检查吗?

    类似

    if (!String.IsNullOrEmpty(e.Row.Cells[4].Text))
        e.Row.Cells[4].Text = Convert.ToDateTime(e.Row.Cells[4].Text).ToString("MM/dd/yyyy");
    else
        e.Row.Cells[4].Text = "-";
    

    【讨论】:

      【解决方案3】:

      如何设置 BoundField.DataFormatString 和 BoundField.NullDisplayText 属性,例如:

      <asp:GridView ID="BoundFieldExample" runat="server">
           <Columns>
                <asp:BoundField DataFormatString="{0:d}" NullDisplayText="Not Found" />
           </Columns>
      </asp:GridView>
      

      上面将以短日期字符串格式显示当前区域性的日期,并为 Null 值显示文本“未找到”。 有关详细信息,请参阅 GridView BoundField Class

      【讨论】:

        猜你喜欢
        • 2019-09-17
        • 2018-03-27
        • 1970-01-01
        • 2018-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-27
        相关资源
        最近更新 更多