开发者

Populating a set of checkboxes based on a file

I'm trying to figure out how to read a file (not created by my program), using a BinaryReader, and checking or unchecking a set of checkboxes accordingly.

I've managed to figure out that the checkboxes are stored as such:

Checkbox 1 = 00 01
Checkbox 2 = 00 02
Checkbox 3 = 00 04
Checkbox 4 = 00 08
Checkbox 5 = 00 10
Checkbox 6 = 00 20
Checkbox 7 = 00 40
Checkbox 8 = 00 60开发者_运维技巧
Checkbox 9 = 00 80
Checkbox 10 = 01 00
Checkbox 11 = 02 00
etc

So if, in the file, checkboxes 1, 2, 6, and 10 where checked the hex value would be: 01 23. How would I break this down so that the correct checkboxes in program would be checked?


I think there is a typo in your example. Checkbox 8 should not be 0060, but rather 0080. So 123 would mean bits: 1, 2, 6, 9 (not 10).

Like this:

Checkbox 01 = 00 01
Checkbox 02 = 00 02
Checkbox 03 = 00 04
Checkbox 04 = 00 08
Checkbox 05 = 00 10
Checkbox 06 = 00 20
Checkbox 07 = 00 40
Checkbox 08 = 00 80
Checkbox 09 = 01 00
Checkbox 10 = 02 00

To check what check box is set you could use code like this:

// var intMask = Convert.ToInt32("0123", 16); // use this line if your input is string
var intMask = 0x0123";
var bitArray = new BitArray(new[] { intMask });
for (var i = 0; i < 16; i++)
{
    var isCheckBoxSet = bitArray.Get(i);
    if (isCheckBoxSet)
        Console.WriteLine("Checkbox {0} is set", i + 1);
}

The output:

Checkbox 1 is set
Checkbox 2 is set
Checkbox 6 is set
Checkbox 9 is set

So your code with checkboxes would be as simple as this:

var checkboxes = new List<CheckBox>();
var intMask = 0x0123;
var bitArray = new BitArray(new[] { intMask });
for (var i = 0; i < 16; i++)
    checkboxes.Add(new CheckBox { Checked = bitArray.Get(i) });


Keep a CheckBox[] or List<CheckBox> with the CheckBox references in the correct order so that you can refer to them by index. You would loop through the individual bit values and use a counter to keep track of the index associated with that bit:

short setBits = 0x0123; # short because it is 2 bytes.
short currentBit = 0x0001;
// loop through the indexes (assuming 16 CheckBoxes or fewer)
for (int index = 0; index < checkBoxes.Length; index++) {
    checkBoxes[index].Checked = (setBits & currentBit) == currentBit;
    currentBit <<= 1; // shift one bit left;
}


This'd be adequate - adjust the upper limit appropriately.

for(int i = 0; i < 15; ++i) {
    Checkbox[i + 1].Checked = (yourbits && (1 << i)) != 0
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜