views:

18

answers:

1

am using C#, VS 2005 and SQL 2000

I have date conversion problem my SQL table having field as below

Fields:

datefrom    
dateto

My SQL query in C# is

string sql = "insert into companymast (cname, datefrom, dateto) values(@cname, @datefrom, @dateto)";

SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("@cname",SqlDbType.Varchar(50)).Values = cname.text;
cmd.Parameters.Add("@datefrom",SqlDbType.Datetime).Values = maskedTextBox1.text;
cmd.Parameters.Add("@dateto",SqlDbType.Datetime).Values = maskedTextBox2.text;
cmd.ExecuteNonQuery();

But the above throw Error Like date non conversion string to date

I have to put date in dd/MM/yyyy format code, 103

so how do i do?

Help me out, please.

A: 

maskedBox1.text is a string. You're assigning that to a SqlParameter's data member, and it tries to convert whatever it receives to the data type you request.

A more solid solution would be to convert to DateTime explicitly, and pass the converted value to the SqlParameter. This way, you have more control over the conversion, and you'll see exactly where and why it goes wrong when it does. Example:

DateTime fromDate = DateTime.Parse(maskedTextBox1.text);
cmd.Parameters.Add("@datefrom",SqlDbType.Datetime).Values= fromDate;

For DateTime.Parse, see: http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

tdammers
is it accept datetime format (DD/MM/YYYY) ?.
mahesh
Depends on the `CultureInfo` it uses, which in turn defaults to the current thread's culture, but can be overridden (details should be in the MSDN documentation). For user input, it is considered good practice to use the user's culture. If you want to be on the safe side, use a `Calendar` control instead of the `TextBox`, then you don't have to worry about the date's textual representation.
tdammers