The way you are giving the values to each of the check boxes is as if each of them represents a bit.
The weight of each bit is a function of its position in the binary representation:
From right to left the weights are as follows:
Posição 0 - 2^0 = 1
Posição 1 - 2^1 = 2
Posição 2 - 2^2 = 4
Posição 3 - 2^3 = 8
Posição 4 - 2^4 = 16
Posição 5 - 2^5 = 32
Posição 6 - 2^6 = 64
Posição 7 - 2^7 = 128
Its decimal value is equal to the sum of the weights whose bits are set(value 1).
If you have checkbox 2 and checkbox 4 checked is the equivalent of binary representation 00000110
= 6
To know if a bit is set to a decimal value use the bitwise logic function:
(b & (1 << pos)) != 0;
This expression returns true
if the bit in position pos number b is set.
Implementation:
We’ll use the property Tag of each Checkbox to store the equivalent of its position in a binary representation number:
checkBox2.Tag = 1;
checkBox4.Tag = 2;
checkBox8.Tag = 3;
checkBox16.Tag = 4;
Let’s create two auxiliary methods.
//Retorna o peso do CheckBox
private int getPeso(CheckBox checkBox)
{
return (int)Math.Pow(2,checkBox.Tag)
}
// Retorna true se a posição 'pos' em 'valor' está setada
private bool needToCheck(int valor, int pos)
{
return (valor & (1 << pos)) != 0;
}
To be able to access Checkbox in a foreach let’s put them in a Dashboard
Method for calculating the value to be stored in the bank:
private int getValor()
{
int valor = 0;
foreach (Control control in panel1.Controls)
{
if (control is CheckBox)
{
if(control.Checked) valor = valor + getPeso(control);
}
}
return valor;
}
Method to check the Checkbox depending on the value stored in the bank.
private void doChecks(int valor)
{
foreach (Control control in panel1.Controls)
{
if (control is CheckBox)
{
control.Checked = needToCheck(valor, control.Tag);
}
}
}
Utilizing
To calculate and store the value:
int valor = getValor();
gravarValorNoBanco(valor);
To check the Checkbox
int valor = lerValorDoBanco();
doChecks(valor);
Note that this code does not need to be changed, whatever the number of Checkbox’s
If you want to do it in a more direct way not using the Panel nor Checkbox.Tag
Calculate:
int valor = 0;
if(checkBox2.Checked) valor = valor + 2;
if(checkBox4.Checked) valor = valor + 4;
if(checkBox8.Checked) valor = valor + 8;
if(checkBox16.Checked) valor = valor + 16;
gravarValorNoBanco(valor);
Check:
int valor = lerValorDoBanco();
checkBox2.Checked = (valor & (1 << 1)) != 0;
checkBox4.Checked = (valor & (1 << 2)) != 0;
checkBox8.Checked = (valor & (1 << 3)) != 0;
checkBox16.Checked = (valor & (1 << 4)) != 0;
Could not create an if with possible combinations?
– Marconi
Yeah, I think I......
– Rafael Spessotto