I’m using SQL Server 2008 and my fields have DATE type but in Visual Studio in my program when I read may data it shows me DATE & TIME what should I do? I try to cast my fields in SELECT query of my program but it gives me some error,how can I solve this problem?
This is my behind code:
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection(Class1.CnnStr);
SqlDataReader reader;
cmd.CommandText = "select ContractStartDate,MandateValidDate from table where BrokerName=@BrokerName";
cmd.Connection.Open();
cmd.Parameters.AddWithValue("@BrokerName", BrokerName_txt.Text);
reader = cmd.ExecuteReader();
if (reader.Read())
{
ContractStartDate_txt.Text = Convert.ToDateTime(reader["ContractStartDate"]).ToString("dd/MM/yyyy");
MandateValidDate_txt.Text = Convert.ToDateTime(reader["MandateValidDate"]).ToString("dd/MM/yyyy");
reader.Close();
}
cmd.Connection.Close();
}
and because I want to save data after read them it gives me error:
Conversion failed when converting date and/or time from character string.
You use Convert.ToDateTime() to convert the strings returned from the database first, later by using DateTime.ToString(“dd/MM/yyyy”) you can get only Date value from the Date & Time.