ASP.Net GridView RowDataBound Error: String was not recognized as a valid DateTime

Last Reply 24 days ago By dharmendr

Posted 24 days ago

I have table in which have two column of INTIME and OUTtime

Empid INTIME OUT TIME
1001   2018-11-11 08:00pm
1002 2018-11-11 08:00am  

when i pass null value into table it raising exception String was not recognized as a valid DateTime.

on page loading 

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox txtEntryDate = e.Row.FindControl("txtEntryDate") as TextBox;
                TextBox txtEndDate = e.Row.FindControl("txtEndDate") as TextBox;
                 
                DateTime startDate = Convert.ToDateTime(txtEntryDate.Text);
                DateTime endDate = Convert.ToDateTime(txtEndDate.Text);
                TextBox txtHours = e.Row.FindControl("txtHours") as TextBox;

Behind Button

        protected void TimeSpan(object sender, EventArgs e)
        {
            GridViewRow row = (sender as TextBox).NamingContainer as GridViewRow;
            string txtINTIME= (row.FindControl("txtINTIME ") as TextBox).Text;
            string txtTime= (row.FindControl("txtTime") as TextBox).Text;           
            TimeSpan timeSpan = Convert.ToDateTime(txtEndTime) - Convert.ToDateTime(txtINTIME );

please guide thanks

Posted 24 days ago

Hi akhter,

You need to check IsNullOrEmpty condition to avoid the error.

if (e.Row.RowType == DataControlRowType.DataRow)
{
    TextBox txtEntryDate = e.Row.FindControl("txtEntryDate") as TextBox;
    TextBox txtEndDate = e.Row.FindControl("txtEndDate") as TextBox;
    if (!string.IsNullOrEmpty(txtEntryDate.Text) && !string.IsNullOrEmpty(txtEndDate.Text))
    {
        DateTime startDate = Convert.ToDateTime(txtEntryDate.Text);
        DateTime endDate = Convert.ToDateTime(txtEndDate.Text);
        TextBox txtHours = e.Row.FindControl("txtHours") as TextBox;
        TextBox txtDays = e.Row.FindControl("txtDays") as TextBox;
        txtHours.Text = endDate.Subtract(startDate).Hours.ToString();
        txtDays.Text = endDate.Subtract(startDate).Days.ToString();
    }
}

 


Posted 24 days ago

Hi akhter,

Same way you can check with IsNullOrEmpty condition in TimeSpan to avoid the error.

protected void TimeSpan(object sender, EventArgs e)
{
    GridViewRow row = (sender as TextBox).NamingContainer as GridViewRow;
    string txtINTIME = (row.FindControl("txtINTIME ") as TextBox).Text;
    string txtTime = (row.FindControl("txtTime") as TextBox).Text;
    if (!string.IsNullOrEmpty(txtINTIME) && !string.IsNullOrEmpty(txtTime))
    {
        TimeSpan timeSpan = Convert.ToDateTime(txtTime) - Convert.ToDateTime(txtINTIME);
    }
}