Link to home
Start Free TrialLog in
Avatar of allanmark
allanmark

asked on

Check value of a bit field in a dataset

Greetings

I am trying to check the value of a bit field and based on that, to update a label. I am getting an erro:
Error      1      Operator '==' cannot be applied to operands of type 'object' and 'bool'      D:\MyStuff - Allan\Training\School_Keeper_ASP\Pages_Admin\Lookup_Religion.aspx.cs      74      13      D:\...\School_Keeper_ASP\

My code:
if (dsReligions.Tables["Religions_List"].Rows[lbxReligions.SelectedIndex]["RL_System"] == true)        
            Label4.Text = "System";
        else
            Label4.Text = "NON System";

My sql, that ceated the table:
CREATE TABLE [dbo].[Religions_List](
  RL_No                  smallint IDENTITY(1,1) not null,
  RL_Name            varchar(50) not null,
  RL_System            bit not null default(0),
CONSTRAINT [PK_Religions_List] PRIMARY KEY.......

ASKER CERTIFIED SOLUTION
Avatar of Elvio Lujan
Elvio Lujan
Flag of Argentina image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
1 means true
0 means false
Avatar of allanmark
allanmark

ASKER

int xyz = (int)dsReligions.Tables["Religions_List"].Rows[lbxReligions.SelectedIndex]["RL_System"];
        if ((int)dsReligions.Tables["Religions_List"].Rows[lbxReligions.SelectedIndex]["RL_System"] == 1)        
            Label4.Text = "System";
        else
            Label4.Text = "NON System";

ERROR:  Specified cast is not valid.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Got it!!

Did as you suggested - the break point thingy ... value was TRUE. SO I played around and:

if ((BOOL)dsReligions.Tables["Religions_List"].Rows[lbxReligions.SelectedIndex]["RL_System"] == true)        
            Label4.Text = "System";
        else
            Label4.Text = "NON System";


THANK YOU!!!
As a follow up note:

SQL Server data types do correspond to CLR data types:
bigint -> long
int -> int
smallint -> short
tinyint -> byte
bit -> bool

Be careful to always explicitly cast the result of a function (such as the column indexer of a datatable row, or the GetValue method of a data reader) to the CLR type you want before comparing to other values or assigning to variables.
e.g.

bool blnSystem = (bool)dsReligions.Tables["Religions_List"].Rows[lbxReligions.SelectedIndex]["RL_System"];

short shNo = (short)myReader.GetValue(0); // same as myReader.GetInt16(0)

All you have to be careful of are null database values - if you could have a NULL in a column, you can use a nullabe data type:

short? shNo = (short)myReader.GetValue(0); // same as myReader.GetInt16(0)

Andy