Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I'm using SQLserver 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 qives me some error,how can I solve this problem?

this is my behind code:

C#
<pre>  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 = reader["ContractStartDate"].ToString();
                MandateValidDate_txt.Text = reader["MandateValidDate"].ToString();
                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.
Posted

1 solution

Change this part:
C#
ContractStartDate_txt.Text = reader["ContractStartDate"].ToString();
                MandateValidDate_txt.Text = reader["MandateValidDate"].ToString();


TO:
C#
ContractStartDate_txt.Text = reader["ContractStartDate"].ToString("MM:dd:yyyy");
                MandateValidDate_txt.Text = reader["MandateValidDate"].ToString("MM:dd:yyyy");


If this doesn't fix, here for your reference:
http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx[^]

Regards,
Eduard
 
Share this answer
 
Comments
kitykity 7-Dec-11 4:08am    
Thank you so much!
[no name] 7-Dec-11 4:16am    
welcome :)
kitykity 7-Dec-11 5:08am    
but this error is continued what should I do now?

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