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:
- protected void DropDownList2_SelectedIndexChanged(object sener, EventArgs e)
- {
- 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";
- SqlConnection con = new SqlConnection(@"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;");
- con.Open();
- SqlCommand cmd = new SqlCommand(query, con);
- DropDownList2.SelectedValue.GetType();
- cmd.Parameters.Add("@USER", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;
- var date = DateTime.ParseExact(DropDownList2.SelectedValue, "yyyy/MM/dd hh:mm:ss", null);
- cmd.Parameters.Add("@DATE", SqlDbType.DateTime).Value = date;
-
- SqlDataReader reader = cmd.ExecuteReader();
- GridView1.DataSource = reader;
- GridView1.DataBind();
- con.Close();
- }
An error is throwing on the line var date = DateTime.ParseExact 'String was not recognized as valid DateTime'