简体   繁体   中英

asp.net formatting dateTime in gridview

I'm binding a gridview dynamically from a table in my database I have called "Sessions". I get the information from a method using a linq query that is something like this:

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

Sessions contains a dateTime field that I want to minimize to just display the date (month/day/year). From what I've read through google searches, the solution is to specify the formatting in the aspx markup of the gridview using something like:

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

It doesn't seem to work and still shows the time after the date. Is there something I'm missing? Help much appreciated!

Try:

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

See this helpful site for more formatting options:

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

Implement the OnDataBinding event for the TextBox in the grid.

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

Then in your code behind implement the OnDataBinding event:

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

I prefer to have all code in the codebehind and nothing in the aspx page but you could also imbed it there as well. Here is a link to a thread where I describe why I prefer to do it in codebehind:

OnDataBinding vs Inline: pros, cons and overhead

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

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

Gridview support date formatting through DataFormatString. For example-

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

and its look like this-


15-Oct-2013
12-Oct-2013
11-Oct-2013

<asp:Label ID="lblDateBudget" runat="server" Text='<%# Eval("DateBudget", "{0:MM/d/yyyy}")%>'></asp:Label>

Hello Friends, Here is the another kind of solution of the problem which you have defined above. You just set your datatype date not datetime and try access in this way. I hope this would be helpfull for you.

I think you datetime variable is evaluated as a String. Try casting it to a DateTime.

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