Convert DateTime.MinValue of a asp.net GridView Column to a String Literal "Never"

Description

Here, the GridView is displaying a standard registered Member Details from SQL Database. One of the fields is the Last Login Date, which displays the member’s last date of login. Now, if the member has never logged in to the system it was displaying the DateTime.MinValue (1/1/0001), which was not optimum. So it was decided that for the DateTime.MinValue the GridView column should display a string “Never”.

Solution

The solution is to apply the if-else conditioning for the ‘Last Login Date’ column. First of all select the option ‘Convert the selected Column into a Template Field‘.

You will see that in the source, certain templates have been added. In the of that column, a Label has been added whose text property is bound to the column Last Login Date. Now for the text property of the Label we write the following code.


<ItemTemplate>
	<asp:Label ID="lblLastLogin" runat="server" Text='<%# (Eval("LastLoginDate", "{0:d}")=="1/1/0001" ? "Never" : Eval("LastLoginDate")) %>'></asp:Label>
</ItemTemplate>

Explanation

This is the standard if-else conditioning. Here we are formatting the Date Time field to Short Date Time ({0:d}) i.e. we are removing the time component from it. Then we’re checking its value against the string ‘1/1/0001’ (min date value). If true, then the value will be replaced by the string ‘Never’ otherwise the full date time value will be displayed (including the time component).

 

Advertisements

One thought on “Convert DateTime.MinValue of a asp.net GridView Column to a String Literal "Never"

  1. GustavoZ January 14, 2017 / 18:03

    Excelente, gracias

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s