Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a web forms application that is connected to a sql server database. In my .net solution I have a Business Object Class that has the following checkbox fields defined as boolean data types and their default value is being set to false. Example Below:

C#
public class AccountTracker
   {
        public bool ModemRequirement { get; set; }
        public bool ModemConnectionToNetworkDevice { get; set; }
        public bool PasswordProtected { get; set; }
   }

public AccountTracker()
        {ModemRequirement =false;
         ModemConnection = false;
         PasswordProtected=false;
</pre>


this works fine in my .net solution but in my sql server database the datatype for those same fields is a bit (0 or 1).

I'm hoping that someone can post some psuedocode that will show how to convert from bool to bit. Here is one of the things I've tried so far.

C#
if (modemrequirement.Checked = true)
{
    modemrequirement = 1;
}
else
{modemrequirement.Checked != true)
{
modemrequirment = 0
}


Any ideas or suggestion on how to properly approach this issue?
Posted
Comments
[no name] 20-Jul-15 14:15pm    
Not sure what you problem is exactly
if (modemrequirement.Checked)
{
modemrequirement = 1;
}
else
{
modemrequirment = 0
}
should work for you. If not you need to tell us the actual problem that you are having.
[no name] 20-Jul-15 14:18pm    
Especally than something like
if (modemrequirement.Checked "=" true)
can't happend. I only know it from c++ there it takes assignement. Maybe (I hope) in c# it results in a Compiler error
[no name] 20-Jul-15 14:25pm    
Why would you think that would be a compile error? It's valid syntax.
Member 11820531 20-Jul-15 14:57pm    
As of right now using the same code in your comment and in my op, the error reads cannot implicitly convert type 'int' to 'System.UI.Webcontrols.CheckBox'
[no name] 20-Jul-15 15:03pm    
Well then I would suggest that you stop using the same variable name to mean different things. According to your code, you are using modemrequirement to mean a check box and an integer variable.

1 solution

bool / Boolean in .NET and bit in SQL are the same type. There is no conversion required.

When you're reading a bit field from SQL, it's already a bool; either cast the value to bool, or use the Field<bool> extension method:
C#
bool theValue = (bool)reader["YourBitColumn"];
bool theValue = reader.Field<bool>("YourBitColumn");


When you're passing a bool as a bit parameter to a query, just pass it in:
bool theValue = true;
command.Parameters.AddWithValue("@YourBitParameter", theValue);
 
Share this answer
 

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