【问题标题】:Populating a set of checkboxes based on a file根据文件填充一组复选框
【发布时间】:2011-09-08 14:37:26
【问题描述】:

我试图弄清楚如何使用BinaryReader 读取文件(不是由我的程序创建的),并相应地选中或取消选中一组复选框。

我已经设法弄清楚复选框是这样存储的:

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

因此,如果在文件中选中复选框 1、2、6 和 10,十六进制值将是:01 23。我将如何分解它以便检查程序中的正确复选框?

【问题讨论】:

    标签: c# .net winforms binary bitarray


    【解决方案1】:

    我认为您的示例中有错字。复选框 8 不应该是 0060,而是 0080。所以 123 表示位:1、2、6、9(不是 10)。

    像这样:

    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
    

    要检查设置的复选框,您可以使用如下代码:

    // 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);
    }
    

    输出:

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

    所以你的带有复选框的代码就这么简单:

    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) });
    

    【讨论】:

    • +1 表示BitArray。我一定对小玩意太舒服了。我宁愿自己使用BitArray,这取决于可能维护代码的其他人。
    【解决方案2】:

    以正确的顺序保留CheckBox[]List&lt;CheckBox&gt;CheckBox 引用,以便您可以按索引引用它们。您将遍历各个位值并使用计数器来跟踪与该位关联的索引:

    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;
    }
    

    【讨论】:

      【解决方案3】:

      这就足够了 - 适当调整上限。

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

      【讨论】:

        猜你喜欢
        • 2015-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-03
        相关资源
        最近更新 更多