【问题标题】:I have modified data in a datatable. How do I get this modified data back into the table?我修改了数据表中的数据。如何将修改后的数据重新放入表中?
【发布时间】:2019-01-19 05:14:10
【问题描述】:

我修改了数据表中的数据。尽管我只需要日期,但 ExpireDate 列返回日期 + 时间。我成功地阅读了每一行以返回正确的格式,但是如何将这个修改后的日期列返回到表格中,以便在我的网络表单中显示它?

con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
    {
       DataTable dt = new DataTable();                           
       foreach (DataRow dr in dt.Rows)
       {
          dr["ExpireDate"] = DateTime.Parse((dr["ExpireDate"].ToString())).ToShortDateString();
       }                                                      
       sda.Fill(dt);
       tblBoard.DataSource = dt;
       tblBoard.DataBind();
       con.Close();
    }

这是网络表单:

<asp:GridView ID="tblBoard" runat="server" AutoGenerateColumns="false">
    <Columns>                
        <asp:BoundField DataField="FirstName" HeaderText="First Name" />
        <asp:BoundField DataField="LastName" HeaderText="Last Name" />
        <asp:BoundField DataField="ExpireDate" HeaderText="Expire Date" />               
    </Columns>
</asp:GridView>

旧的日期格式仍然显示在表格中。

【问题讨论】:

    标签: c# asp.net datatable


    【解决方案1】:

    不要更改存储在DataTable 本身中的值...相反,通过指定DataFormatString 来修改它在向用户显示时的显示方式:

    <asp:BoundField DataField="ExpireDate"
                    HeaderText="Expire Date"
                    DataFormatString="{0:dd/MM/yyyy}" />
    

    数据和数据的表示是两个不同的东西。我想您可以使用字符串列,然后只显示您想要显示的日期部分,但使用格式更好,因为有人可以轻松介入并更改未来日期的显示方式,而无需接触数据。

    【讨论】:

      【解决方案2】:

      如果您从后端更改日期格式并且该日期未反映在前端,请尝试删除浏览器的捕获,然后重试。

      另外,另一种解决方案是无需在后端使用 for 循环。直接将您的表格数据绑定到网格视图数据源和前端仅设置DataFormatString。

      <asp:BoundField DataField="ExpireDate" HtmlEncode="false" 
      DataFormatString="{0:d}" />
      

      <asp:BoundField DataField="ExpireDate" HtmlEncode="false" 
       DataFormatString="{0:MM/dd/yyyy}" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-12
        • 2010-11-22
        • 2010-11-19
        • 2012-01-24
        • 1970-01-01
        相关资源
        最近更新 更多