Home > Software engineering >  How to show/hide label depence of the position of boolean numbers "0" or "1" are
How to show/hide label depence of the position of boolean numbers "0" or "1" are

Time:11-08

if in textbox.text the value is 011, show label2 and label3 and hide label1.

If in textbox.text the value is 101 show label1, hide label2, show label3.

If in textbox.text the value is 000 hide all the labels.

If in textbox.text the value is 111 show all the labels (label1 ,label2, label3).

The same if the value in textbox.text is 00011111000001101011.

        //Count how digits are in textbox
       int result = textBox1.Text.Count(c => char.IsDigit(c));
       label1.Text = result.ToString();
       //find the position of '1' or '0' are
                                     

CodePudding user response:

You can start by putting your labels into an array. You could do this after the call to InitializeComponent();:

public class Form1
{
    private readonly List<Label> _labels;

    public Form1()
    {
        InitializeComponent();
        _labels = new List<Label>() { label1, label2, label3, label4, label5 };
    }

Then we can add a method that takes a string of 0s and 1s, loops through it, and sets the visibility of the corresponding labels in the _labels list:

private void SetLabelVisibility(string visString)
{
    // get the maximum number of possible labels to update
    // this is the smaller of the number of 0s and 1s in the string,
    // and the number of labels in _labels
    int maxLen = Math.Min(visString.Length, _labels.Count);

    for (int i = 0; i < maxLen;   i)
    {
        // check if the character is 0, 1, or other
        switch (visString[i])
        {
            case '0': // set to invisible
                _labels[i].Visible = false;
                break;
            case '1': // set to visible
                _labels[i].Visible = true;
                break;
             default: // invalid character
                 throw new ArgumentException(nameof(visString));
         }
    }
}

So calling SetLabelVisibility("01101"); will leave labels 2, 3, and 5 visible, but hide labels 1 and 4.

  • Related