views:

1334

answers:

3

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!

+3  A: 

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

JerSchneid
Thanks all. This one worked on first try. Haven't tried the others so they probably work too. I appreciate it!
A: 

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

Christian Hagelid
+1  A: 

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:

http://stackoverflow.com/questions/702343/ondatabinding-vs-inline

Kelsey