fred brass

fred brass

  • NA
  • 2
  • 626

Changing a value to datetime c#

Apr 18 2018 4:59 AM
I am trying to change a value selected in a drop down list to a datetime. The values bound to the drop down list are from a Date column under a datetime2 type, however they change when bound to the drop down list. When the date in the drop down list is selected it should populate a gridview according to the value, but because the format is changed the 'where' clause in my sql statement is invalid.
 
My code is as follows:
  1. protected void DropDownList2_SelectedIndexChanged(object sener, EventArgs e)  
  2. {  
  3. String query = "SELECT Stock_Take.Username, Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity, Stock_Take.StockTakeIDNew FROM Item INNER JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID INNER JOIN Stock_Take ON Stock_Take_Item.StockTakeIDNew = Stock_Take.StockTakeIDNew where Stock_Take.Username = @USER AND Stock_Take.StockDate = @DATE";  
  4. SqlConnection con = new SqlConnection(@"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;");  
  5. con.Open();  
  6. SqlCommand cmd = new SqlCommand(query, con);  
  7. DropDownList2.SelectedValue.GetType();  
  8. cmd.Parameters.Add("@USER", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;  
  9. var date = DateTime.ParseExact(DropDownList2.SelectedValue, "yyyy/MM/dd hh:mm:ss"null);  
  10. cmd.Parameters.Add("@DATE", SqlDbType.DateTime).Value = date;  
  11. // DateTime date = Convert.ToDateTime(DropDownList2.SelectedValue.ToString());  
  12. SqlDataReader reader = cmd.ExecuteReader();  
  13. GridView1.DataSource = reader;  
  14. GridView1.DataBind();  
  15. con.Close();  
  16. }  
An error is throwing on the line var date = DateTime.ParseExact 'String was not recognized as valid DateTime'

Answers (3)