R – How to change the direction of a BoundField in GridView

asp.netboundfieldgridview

Sorry if my question seems to simple .

Right now in the BoundField of my GridView some data display like "12/11/1381" that i wanna display like "1381/11/12" (opposite direction) .

I know i could change the direction via rtl and ltr in TemplateField. But because of some reason i can't convert my boundfield to templatefield.

I looked through all BoundField properties in order to change direction , but i found nothing.

I think that should be done in RowDataBound event of GridView , But i don't know how !?

What do you think at this case ?
Thanks in advance.

Best Answer

Ok, since it's a date which was input as string, there are at least 2 ways you can do it.

Method 1
Databind the string as a Date object instead of String. As I do not now the exact date format of the original date, dd/MM/yyyy or MM/dd/yyyy, you'll have to figure it out yourself.

If you can do that, just add this to the "BoundField" element:

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

or

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

Method 2
Manipulate the text in ROwDataBound oevent. I've done a crude one here which can be polished up. You should probably manipulate them as Date objects.

In the ASPX:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
 onrowdatabound="GridView1_RowDataBound">

CodeBehind:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType != DataControlRowType.DataRow)
        return;
    // assuming the date is at cell index 1
    string[] arr = e.Row.Cells[1].Text.ToString().Split('/');
    e.Row.Cells[1].Text = string.Format("{0}/{1}/{2}", arr[2], arr[1], arr[0]);
}