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 (with a value of 1).
If you have checkbox 2 and checkbox 4 checked it is the equivalent of the 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 of the number b is set.
Implementation:
Let's use the Tag property of each CheckBox to save the equivalent of its position in a number in binary representation:
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;
}
In order to be able to access CheckBox in a foreach we will place them in a Dashboard
Method to calculate the value to save 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 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);
}
}
}
Utilization
To calculate and save the value:
int valor = getValor();
gravarValorNoBanco(valor);
To check CheckBox
int valor = lerValorDoBanco();
doChecks(valor);
Please note that this code does not need to be changed, whatever CheckBox's number
If you want to do it more directly, do not use the 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;