9

In the olden days before asp.net 4.5 we could easily bind a date to a Gridview, Formview or other databound control and make it look presentable with a simple format string.

            <asp:TextBox 
                ID="DateFieldTextBox" 
                runat="server" 
                Text='<%# Bind("DateField","{0:d}") %>'/>

The new, strongly typed model binding is a bit more difficult.

            <asp:TextBox 
                ID="DateFieldTextBox" 
                runat="server" 
                Text='<%# BindItem.DateField %>'/>

will work, but produces the full date/time string rather than just the date.

            <asp:TextBox 
                ID="DateFieldTextBox" 
                runat="server" 
                Text='<%# BindItem.DateField.ToShortDateString() %>'/>

.. this should work, but it produces a compile time error "Invalid code syntax for BindItem". Item.DateField.ToShortDateString() works but does not bind on the postback.

For now we've reverted to the old syntax, but we would love to get the modern compile time checking but still be able to format the dates nicely. Anyone else ran into this before?

John Hoge
  • 2,371
  • 2
  • 20
  • 24
  • also doesn't work when trying this: `'<%# string.Format(CultureInfo.CurrentCulture, "{0:d}", BindItem.InfoBirthday) %>'`, it says: Compiler Error Message: CS0103: The name 'BindItem' does not exist in the current context – Nikola Bogdanović Jul 22 '13 at 22:34
  • http://stackoverflow.com/questions/17824427/how-do-i-format-a-date-pulled-from-a-database/17831740#17831740 – senthilkumar2185 Jul 29 '13 at 15:45
  • http://stackoverflow.com/questions/17824427/how-do-i-format-a-date-pulled-from-a-database/17831740#17831740 – senthilkumar2185 Jul 29 '13 at 15:46
  • @senthilkumar: did you read the question at all? we need the alternative for the new Model Binding - and don't ever use the old `Eval` (late bound reflection), but `Container.DataItem` instead: `string.Format("{0:d}", ((DataRowView)Container.DataItem)["DateField"])` – Nikola Bogdanović Jul 29 '13 at 23:17

5 Answers5

2

For displaying data in grid view, You can do Item.DateField.ToShortString() and it will work as it is one way data binding. i.e you are displying what is in the record already. BindItem.DateField.ToDateString() will convert object from DateTime to string which will result in error as you are already seeing. You can keep using Bind(expression,format) in formview while editing field or for accpting new entry.

Anand
  • 1,440
  • 8
  • 11
2

I struggled with this for quite some time. My solution was to combine Data Annotations in the data model along with the use of a DynamicControl in my FormView. I've assumed this is a WebForms project vs. an MCV project.

Read a little on the realm of data access in WebForms. It's one of MS's better write-ups on WebForms data access/presentation controls and includes references to the DynamicControl.

//I know you want this, and I did too.  It seems like it could/should work, but it doesn't        
<asp:TextBox 
     ID="DateFieldTextBox" 
     runat="server" 
     Text='<%# BindItem.DateField.ToShortDateString() %>'/>

//This works, but you also need to use the Data Annotations in your model.
<asp:DynamicControl
     ID="DateFieldTextBox"
     runat="server"
     DataField="DateField"
     Mode="Edit" />

//sample model annotations in your object class
  [Column(TypeName = "date"), DataType(DataType.Date), DisplayFormat(DataFormatString = "  {0:MM/dd/yyyy}", ApplyFormatInEditMode = true )]
  public DateTime DateField { get; set; }

I'll be using this pattern because I need two-way model binding with the ability to present dates in the right format (as well as currency, etc.). It is really unfortunate that the TextBox control doesn't handle formatting the model data like this fully. DataAnnotations are ignored in this context. Two-way binding works if there's no formatting, but not if you need formatting. It seems like an incomplete WebForms implementation IMO.

On the otherhand, using the DynamicControl works, but you get no Intellisense on the DataField property that would provide you members of the model while coding. What???? Another incomplete, and less preferred, solution.

secretwep
  • 706
  • 1
  • 12
  • 28
  • The idea here worked for me (binding in a repeater). Annotated the property with DisplayFormat and used the DynamicControl instead of BindItem.Bind. Intellisense also working inside the dynamic control too, which is nice. – PaulTheCyclist Nov 13 '14 at 15:51
1

At last after struggling for two days I get a solution for this two way model binding issue for formatted field value. Just remove the single or double quotation mark "" or '' after the property text of the TextBox. It works for me like a charm!! But if you use the TextMode property of the TextBox to Date, remove it. Cause, it will not display a value from server or DB. If you want to use a datepicker or calendar, you can simple add an AJAX CalendarExtender control to pick a date from calendar.

<asp:TextBox ID="DateFieldTextBox" runat="server" Text=<%# Bind("DateField","{0:d}") %>/>
EsseyG
  • 46
  • 1
  • 4
0

Apologies for resurrecting this thread, but did you consider adding Data Annotations to your model class? In other words:

using System.ComponentModel.DataAnnotations;

[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateField { get; set; }

This seems to work for me, though I don't know the particulars of your case.

karfus
  • 869
  • 1
  • 13
  • 20
0

You can also check if you are using Template Field.

<asp:TemplateField HeaderText="Submission Date">
<ItemTemplate>
     <%# Bind("dbDate","{0:dd/MM/yyyy HH:mm:tt}") %>
</ItemTemplate>
</asp:TemplateField>