Friday, June 12, 2015

Bind Date Time in Gridview

During development, when try to bind data to a date time control in gridview, it successfully insert data in DB from the date time control. When try to retrieve back from DB and bind it to the date time control. There is always an empty field. So here my solution.

At aspx page, add a control to hold the value and make it visible to false.

<asp:Label ID="lblDate" Text='<%#Eval("PurchaseDate", "{0:dd MMM yyyy}") %>' runat="server" Visible="false" />

When the page load or any action trigger the reload of the gridview, the RowDataBound will bound the data row by row. So that we can use RowDataBound method to bind the data from label to the date time control.
Below is the code behind snippet.

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblDate = (Label)e.Row.FindControl("lblDate");
                DateTimeControl dtDate = (DateTimeControl)e.Row.FindControl("PurchaseDate");

                if (!string.IsNullOrEmpty(lblDate.Text))
                {
                    dtDate.SelectedDate = Convert.ToDateTime(lblDate.Text);
                }
            }
}

No comments:

Post a Comment