Introducing HTML 5 Date Input Type in ASP.Net

Introduction

Today we'll learn the new input types that are provided by HTML 5 such as Date, URL and so on. We'll use the Date input type here in the Grid View. When we use a Date input type in a TextBox a date picker is displayed in the browsers such as Chrome and Opera. We can use the Date type format (ISO format) to show the date in the text box.

Let's discuss this in brief. Suppose we have developed an ASP.NET Web Application with the following scenario:

  • Create an application in Visual Studio
  • Add a web form and in the Grid View, we have generated a database table
  • We are also performing the Insert, Update and Delete operations in it.

So, suppose we have a date column named DateofBirth in the GridView so that the user can change the date by entering the value. So, to make the date entry easy we'll use the HTML 5 date input type. A BoundField of a GridView always uses a plain TextBox. To use a HTML 5 date input type we need to add a TemplateField in the GridView. We need to modify the EditItemTemplate of the TemplateField with the following markup:

<asp:TemplateField HeaderText="Date of Birth">

    <ItemTemplate>

        <asp:Label ID="LblDob" runat="server" Text='<%# Bind("DateofBirth"%>'></asp:Label>

    </ItemTemplate>

    <EditItemTemplate>

        <asp:TextBox ID="TxtDob" runat="server" Text='<%# Bind("DateofBirth"%>' TextMode="Date"></asp:TextBox>

    </EditItemTemplate>

</asp:TemplateField>

In the preceding markup, we've modified the DateofBirth column in the EditItemTemplate. Now when we run the application in Chrome and while clicking on the Edit button, you'll see the date TextBox changed as in the following screenshot:

Use of HTML 5 Date Input Type

As you can see, instead of showing the respective date of the database value, it is showing the date picker control. A HTML 5 date input type control is the reason for this. The default format of the .NET for displaying the date is MM/dd/yyyy so that the date-picker fails to show the date correctly.

To overcome this, we need to add a string type of format in the HTML 5 Date Input Type. Modify the markup with the following highlighted markup:

<EditItemTemplate>

    <asp:TextBox ID="TxtDob" runat="server" Text='<%# Bind("DateofBirth", "{0:yyyy-MM-dd}"%>' TextMode="Date"></asp:TextBox>

</EditItemTemplate>

Now run the application in the Chrome browser:

DateFormat in Html 5 Date Input

Summary

This article described the use of  the HTML 5 Date Input Type in the GridView in the ASP.NET Web Application. Happy coding and stay updated!

Up Next
    Ebook Download
    View all
    Learn
    View all