Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When i updating cell date in gridview then it is raising issue of
String was not recognized as a valid DateTime.


In Sql table date column type is datetime

What I have tried:

        protected void GridView3_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
     DateTime date2 = Convert.ToDateTime(txtEntryDate.Text);  //Issue in this Code///
           
      GridViewRow row = GridView3.Rows[e.RowIndex];
            int customerId = Convert.ToInt32(GridView3.DataKeys[e.RowIndex].Values[0]);
            string name = (row.FindControl("txtName") as TextBox).Text;
            string country = (row.FindControl("txtCountry") as TextBox).Text;
            string EntryDate = (row.FindControl("txtEntryDate") as TextBox).Text;
            string query = "UPDATE Country SET Name=@Name, Country=@Country, EntryDate=@date2 WHERE CustomerId=@CustomerId";
            con = new SqlConnection("Data Source=DESKTOP-5PJ76B9;Integrated Security=SSPI;Initial Catalog=Institute");
                     {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Parameters.AddWithValue("@CustomerId", customerId);
                    cmd.Parameters.AddWithValue("@Name", name);
                    cmd.Parameters.AddWithValue("@Country", country);
                    cmd.Parameters.AddWithValue("@date2", EntryDate);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            GridView3.EditIndex = -1;
            this.BindGrid();
        }
    }
}
Posted
Updated 24-Nov-18 19:57pm
Comments
Ehsan Sajjad 25-Nov-18 0:59am    
can you show what is the format of date coming as input in the textbox ?
Member 12314309 25-Nov-18 1:31am    
datetimelocal
George Swan 25-Nov-18 1:59am    
Try using DateTime.ParseExact
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=netframework-4.7.2

1 solution

Simple: it isn't a valid date.
It may be to you, and your user - but SQL runs on a different computer and doesn't have access to your users preferences. Instead of passing everything to SQL as a string, use the various TryParse methods to convert them to native types (using the user settings to get it right) and pass the converted value directly to SQL.

C#
DateTime datEntry;
it (!DateTime.TryParse(EntryDate, out datEntry))
   {
   ... report format / value problem to user ...
   return;
   }
...
cmd.Parameters.AddWithValue("@date2", datEntry);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900