Friday, September 23, 2011

Save and load multiple bool values with a single decimal value.

The example below will explain how to store and load multiple bool values from a database with a single decimal value.


-----------------------------------------------------------------------
Save bool values as decimal
-----------------------------------------------------------------------

int options = 0;

options=options | Convert.ToInt32(Option1.Checked); //bitwise OR

options=options << 1; //Shift bits

options=options | Convert.ToInt32(Option2.Checked);

options=options << 1;

options=options | Convert.ToInt32(Option3.Checked);

options=options << 1;

options=options | Convert.ToInt32(Option4.Checked);

options=options << 1;

options=options | Convert.ToInt32(Option5.Checked);


DBService.SaveDetail(options);



-----------------------------------------------------------------------
Load decimal value from database
-----------------------------------------------------------------------

DataRow dr = DBService.GetDetail();

int values = int.Parse(dr["decimal"].ToString());


Load controls
Use binary operators to check each bit
Option1.Checked = ((bool)((options & 1) == 1)); //bitwise AND

options=options >> 1; //Shift bits

Option2.Checked = ((bool)((options & 1) == 1));

options=options >> 1;

Option3.Checked = ((bool)((options & 1) == 1));

options=options >> 1;

Option4.Checked = ((bool)((options & 1) == 1));

options=options >> 1;

Option5.Checked = ((bool)((options & 1) == 1));

Monday, September 12, 2011

Using GetEnumerator()

Testing ASCII values of user input

byte[] _asciiAnswer = Encoding.ASCII.GetBytes(AnswerTb.Text.Trim());

IEnumerator _asciiChars = _asciiAnswer.GetEnumerator();
while (_asciiChars.MoveNext())
{
  byte _char = (byte)_asciiChars.Current;
  if (_char >= 65 && _char <= 90)
    IsUpperCase = true;
}