简体   繁体   中英

Converting datetime object to date only format in asp.net datatable

I am trying to display a SQL server table in asp.net gridview. There are lot of tables in SQL server database and user selects a table and that table should be displayed in gridview. For all the datetime columns in sql server table, I need to display dates only.

I read the data by using SQLDataReader and loaded the data into a datatable. If the cell is of date type, then I am trying to convert it to date only format as shown in below image.

在此处输入图片说明

I tired converting the date using date.toString("MM/dd/yyyy") but unable to edit it in the datatable. The variable a in the image is showing the entire date with time. Can anyone help with the changes required to made so that only date is displayed in the date column.

I initially tried pushing variable b value to datatable but unable to succeed, then I tried to convert it to date again and tried. Nothing changed :(

edit: Here's the code

for (int i =0; i<table.Rows.Count;i++)
{
    DataRow row = table.Rows[i];                                         
    for (int j = 0; j < table.Columns.Count; j++)
    {
        string t = table.Rows[i][j].GetType().ToString();
        if (table.Rows[i][j].GetType().Equals(typeof(DateTime)))
        {
            mydate = DateTime.Parse(table.Rows[i][j].ToString());
            var b = mydate.Month + "/" + mydate.Day + "/" + mydate.Year;
            var c = DateTime.Parse(b.ToString());
            var d = c.ToString("MM/dd/yyyy");
            table.Rows[i].SetField(j, c.ToString("MM/dd/yyyy"));
            var a = table.Rows[i][j];
        }
    }                        
}

It seems like you are tackling a UI issue in your backend code. This should be tackled on the UI side without impacting your actual data. You can accomplish this by applying a format to your bound column or template:

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

OR

<asp:TemplateField HeaderText ="Purchase Date" >
   <ItemTemplate >
   <asp:Label ID="lblDate" runat="server" 
              Text='<%# Eval("PurchaseDate", "{0:MM/dd/yyyy}") %>' />
    </ItemTemplate>
</asp:TemplateField>

EDIT:

@DineshInavolu why don't you try the rowdatabound event and TryParse?

void OrderGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{        
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        DateTime? dateValue = null;
        if(!DateTime.TryParse(e.Row.Cells[1].Text, out dateValue))
            e.Row.Cells[1].Text = dateValue.Value.ToString("MM/dd/yyyy");        
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM