How to format data in GridView with custom format string?
|
|
|
|
|
Downloads
If you are seeing this section and do not see download links, this means that you are not logged into our site. If you already are a member, click on the login link
and login into site and come back to this page for downloading the control files. If you are not a member, click on registration link to
become a Winista member and download the control for free.
In my article Data Formatting in Grid View, I discussed how you can set DataFormatString
property on BoundField column to format the value displayed in that column. But trouble is that this approach
only works if your data type in that column is of type like numeric, datetime. This approach does not work if you have data type
as string. For example in one of cases we had phone numbers in table stored as "NVarChar" and my client wanted to display
it in format (xxx) xxx-xxxx. When I tried to set DataFormatString value to {0:(###) ### ####}, it did not work.
Now your option is converting the data type of that column to something that can be formatted using the format string. For example
in our case the phone numbers could be parsed as Int64. Then we could easily format them to by applying custom formatting string
{0:(###) ### ####}. You will handle OnRowDatabound event and take care of the conversion there. I tried to handle
it in OnRowCreated, unfortunately it does not work. It seems that GridView implementation overrides any test you set in the value at
this stage.
Following is the GridView definition I have in the demo project.
<asp:GridView ID="ctlGridView" runat="server" autogeneratecolumns=False
gridlines=Horizontal onrowdatabound="OnRowDataBound">
<columns>
<asp:boundfield datafield="ID" sortexpression="ProductID" />
<asp:boundfield datafield="FirstName" headertext="First Name" sortexpression="Name" />
<asp:boundfield datafield="LastName" headertext="Last Name" />
<asp:BoundField DataField="DOB" HeaderText="Date Of Birth" HtmlEncode="False" DataFormatString="{0:d}" />
<asp:BoundField DataField="Phone" HeaderText="Phone Number" HtmlEncode="False" />
</columns>
</asp:GridView>
Here is the implementation I have in RowDataBound event handler.
protected void OnRowDataBound(object sender, EventArgs e)
{
GridViewRowEventArgs ea = e as GridViewRowEventArgs;
if (ea.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = ea.Row.DataItem as DataRowView;
Object ob = drv["Phone"];
if (!Convert.IsDBNull(ob))
{
Int64 iParsedValue = 0;
if (Int64.TryParse(ob.ToString(), out iParsedValue))
{
TableCell cell = ea.Row.Cells[4];
cell.Text = String.Format(System.Globalization.CultureInfo.CurrentCulture,
"{0:(###) ###-####}", new object[] { iParsedValue });
}
}
}
}
|