Pregunta

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?

¿Fue útil?

Solución

You could set it from codebehind:

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

Otros consejos

One option would be to create a new class, DateBoundField (or whatever you want to name it), which inherits bound field. In the constructor you just set the DataFormatString to your date format string, then use the DateBoundField everywhere for your dates, when you need to change your date format, just change the format string in the constructor of this class.

    public class DateBoundField : BoundField
    {
        public DateBoundField()
        {
             DataFormatString = "{0:yyyy-MMM-dd}";
        }
    }

I guess I just found the solution, i never used it before so you need to try :-)

Description url not being decoded asp.net

I would try something like:

<%# myFormatString() %>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top