I have a GridView on my aspx page which displays a collection of objects defined by the following class
public class Item
{
public string ItemName{get; set;}
public object ItemValue{get; set;}
}
Then in my aspx markup I have something like this
<asp:GridView ID="MyTable" runat="server">
<Columns>
<asp:BoundField DataField="ItemName" />
<asp:BoundField DataField="ItemValue" />
</Columns>
</asp:GridView>
What I want to know is:
Is there a way to use conditional formatting on the ItemValue field, so that if the object is holding a string it will return the string unchanged, or if it holds a DateTime it will displays as DateTime.ToShortDateString().
Not sure if you can use a BoundField, but if you change it to a TemplateField you could use a formatting function like in this link.
ie something like
Then in your codebehind, you can add a Protected Function
Or you could do something in the OnRowCreated event of the gridview, like in this link
this function is conditional formatting based on whether or not the datavalue is null/is a double
i decided with the Paul Rowland solution and more one thing "if (e.Item.DataItem is DataRowView)":
With BoundField you should modify your Item class.
If you don't want to modify your CodeBehind ther is a sort of trick you can do using a TemplateField:
obviously you can do it for any type of object but maybe your "Text" field would become.. complicated..
by the way.. my CodeBehind for this example was just you class Item and this Page_Load():
and the result was correct ;)
In .NET 2.0 is even easier:
Add this method to code behind: (this example formats a double value as million with 1 digit)
In the aspx code, use this: