如何显示/隐藏布尔数字位置的标签"0"或"1"。窗口窗体



如果在文本框中。文本值为011,显示label2和label3,隐藏label1。

如果在文本框中。文本值为101 show label1, hide label2, show label3

如果在文本框中。文本值为000隐藏所有标签。

如果在文本框中。文本值为111显示所有标签(label1,label2, label3)。

与文本框中的值相同。文本为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
                                     

您可以从将标签放入数组开始。您可以在调用InitializeComponent();:

之后执行此操作。
public class Form1
{
    private readonly List<Label> _labels;
    public Form1()
    {
        InitializeComponent();
        _labels = new List<Label>() { label1, label2, label3, label4, label5 };
    }

然后我们可以添加一个方法,该方法接受0和1的字符串,循环遍历它,并设置_labels列表中相应标签的可见性:

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

因此调用SetLabelVisibility("01101");将保留标签2,3和5可见,但隐藏标签1和4。

最新更新