Search code examples
c#asp.netascxboundfield

Use a variable DataFormatString in asp.net ascx


So I have some code that looks like this:

<asp:BoundField DataField="CreatedOn" HeaderText="Created on" 
SortExpression="CreatedOn" DataFormatString="{0:MMM dd yyyy hh:mm:ss tt}">

This works as I would like it to. However, I want to reuse the date format everywhere in my program. Thus, I want to use a variable instead of the string used above. Something like:

<asp:BoundField DataField="CreatedOn" HeaderText="Created on" 
SortExpression="CreatedOn" DataFormatString="<%=myFormatString%>">

But this totally doesn't work. It prints out literally:

<%=myFormatString%>

I tried Bind, I tried Eval, nothing seems to work. It seems to me this should be really simple, even necessary. Am I the only person in the world who wants to use a DataFormatString more than once? Is this possible or am I a dreamer?


Solution

  • You could set it from codebehind:

    ((BoundField)GridView1.Columns[ColumnIndex]).DataFormatString = myFormatString;