用字符串日期时间填充文本框而没有时间

时间:2013-08-21 19:35:58

标签: c# asp.net datetime

我有一个包含datetime字段的表。我已将其放入datakey和pageload并从gridview中选择它将使用数据库中表的日期时间填充文本框。我不想要时间。在网格视图中,我已经摆脱了时间,但是当我填充文本框时,我无法摆脱它。有什么建议?这是我的代码:(我需要PurchaseDate和WarrantyDate只显示没有时间的日期)

private void PopulateForm(int index)
    {

        var dataKey = grdvwAssetGrid.DataKeys[index];

        if (dataKey != null)
            AssetId = (int)dataKey["Id"];
        if (dataKey != null)
            LocationId = (int)dataKey["LocationId"];
        if (dataKey != null)
            txtVendor.Text = (string)dataKey["Vendor"];
        if (dataKey != null)
            txtSerialNumber.Text = (string)dataKey["SerialNumber"];
        if (dataKey != null)
            txtDescription.Text = (string)dataKey["Description"];
        if (dataKey != null)
            txtType.Text = (string)dataKey["Type"];
        if (dataKey != null)
            txtPrimaryUser.Text = (string)dataKey["PrimaryUser"];
        if (dataKey != null)
            txtPurchaseDate.Text = dataKey["PurchaseDate"].ToString();
        if (dataKey != null)
            txtWarrantyDate.Text = dataKey["WarrantyExpDate"].ToString();
    }

在gridview中,我这样做是为了将日期时间更改为仅日期:

<asp:BoundField DataField="PurchaseDate" HeaderText="Purchase Date" InsertVisible="False" ReadOnly="True" DataFormatString="{0:d}" />
<asp:BoundField DataField="WarrantyExpDate" HeaderText="Warranty Date" InsertVisible="False" ReadOnly="True" DataFormatString="{0:d}" />

3 个答案:

答案 0 :(得分:7)

ToShortDateString()代替ToString()

OR

ToString("d"),这是短日期字符串的格式。

更新:

将您的值转换为DateTime对象,如下所示:

if (dataKey != null)
    txtPurchaseDate.Text = ((DateTime)dataKey["PurchaseDate"]).ToShortDateString();
if (dataKey != null)
    txtWarrantyDate.Text = ((DateTime)dataKey["WarrantyExpDate"]).ToString("d");

答案 1 :(得分:0)

您拥有ToShortDateString以及可以提供给ToString方法的所有可能格式。

答案 2 :(得分:0)

txtPurchaseDate.Text = Convert.ToDateTime(dataKey["PurchaseDate"]).ToString("dd/MM/yyyy");