views:

691

answers:

4

Can anyone help in converting string value in C# to bit equivalent in Sql. I'm trying to bulkcopy the values of a datatable into Sql table. All the values I've in the datatable are in string format. When I try to bulkcopy to SQL table I'm getting an error for bit datatype columns.Can anyone please post the C# code to convert string to bit type before I bulkcopy to SQL table.

Thanks, Vix

A: 

The bit data type in SQL Server matches up to the bool data type in C#. So just convert your strings to bools (using bool.Parse() or your favorite alternative) and you should be set.

Daniel Pryden
Thanks,Daniel.How do I convert string to float for the same scenario.I tried using Convert.ToDouble(str); but it didn't work.Please help
vix
+2  A: 

If your strings are "true" and "false" (ignoring case and whitespace) this will work:

bool bit = bool.Parse(str);

If your strings are something else, you could use:

bool bit = !string.IsNullOrEmpty(str) &&
  (str[0]=='Y' || str[0]=='y' || str[0]=='T' || str[0]=='t' || str[0]=='1');

SQL wants a bool value.

Ray Burns
Thanks Ray.How do I convert string to float for the same scenario.I tried Convert.ToDouble(str); but it didn't work.Please help.
vix
I use double.Parse() for the 'float' SQL data type, but Convert.ToDouble() just calls double.Parse() so it should have worked. Did the Convert.ToDouble() call itself throw an exception, or did SQL reject the resulting value? Also, what data access layer are you using (ie. what calls are you using to submit your data?)
Ray Burns
vix
when I call this method bulkcopy.WriteToServer(dtUpdate); to copy values from datatable to Sql table,I'm getting the error.But when I see the value in the datatable for which it throws the exception it's a valid number.All the values for the column are valid numbers.
vix
The exception you are quoting would happen if the value in dtUpdate is a string and can't be parsed. Some possiblities: Column.DataType is not Double, Column names or order mixed up.
Ray Burns
A: 

SQL Server will recognise "true" and "false" for the bit datatype. Also, zero stores zero, non-zero stores as "1".

Are you sending "true" or true?

If you get the same error with doubles (as per comments to other answers), then I suspect you are sending quotes.

gbn
A: 

can anyone please tell me how to convert bit value in database to string to display checkbox as checked in asp.net page using C#

ChkShowJobs.Checked = (vals[19]);

Thank You, Sam

sam
I'm not sure this is a valid answer to the question, maybe you should consider your own question.
Coding Gorilla