Saturday, November 22, 2008

Bits of Madness

I ran into an odd situation this week while coding a webform with Yes and No radiobuttons using the RadioButtonList control.

Traditionally, Yes and No are presented in a control with Yes being first. Therefore, in a .Net RadioButtonList control, the Index value for Yes is 0 (zero), while the Index value for No is 1. Being the old traditionalist that I am, I assigned 0 to the Value property for No and 1 to the Value for Yes.

This is an unbound control but is sourced to a Bit column in a SQL Server table. A Bit column is referenced in T-SQL as 0 for No and 1 for Yes, for example:

UPDATE mytable SET mybitfield = 0

This would set MyBitField to No.

When I grab this column into a Dataset in Visual Studio and want to convert it into an integer, I use the CInt function. CInt, though, converts a Yes to -1 and No to 0.

So now we have the following for my simple radiobuttons:

Yes No
Control.Index 0 1
Control.Value 1 0
MyBitField 1 0
CInt("mybitfield") -1 0

And this makes my head hurt

The simple solution is to assign Control.SelectedValue to Abs(CInt("mybitfield")) which will convert the -1 to 1 and leave the 0 values as is. But others might scratch their head while reviewing the code.

Another way to simplify this would be if I changed the control so that No came first, changing the control from Yes / No to No / Yes. That, however, goes against the way people think. I don't recall hearing anyone talk about a "No / Yes situation". I guess I could also reverse the assigned Values for the control so that No is 1 and Yes is 0 but that doesn't feel right either.

Sigh. Leave it to Microsoft to complicate something as simple as Boolean logic.

No comments: