【问题标题】:How to open items one by one如何一件一件地打开物品
【发布时间】:2020-06-29 08:38:08
【问题描述】:

我有这个代码:

private void button3_Click(object sender, EventArgs e)
    {
        textBox3.Visible = true;
        textBox4.Visible = true;
        textBox5.Visible = true;
        textBox6.Visible = true;
    }

当我按下button3时,所有文本框都会打开。
但我希望它们一个一个打开。

【问题讨论】:

  • 您想在第一次单击 button3 时打开 textBox3,然后在第二次单击该按钮时打开 textBox4?
  • @WolfgangRoth 是的
  • 尝试使用计数器来计算点击次数。 int counter 应该在类级别的方法之外声明。然后根据计数器编号切换按钮
  • 这样您就可以检查其中一个文本框是否可见,如果不激活它...: if (!textBox3.Visible) textBox3.Visible = true;else if (!textBox4.Visible) textBox4.Visible = true; else if (!textBox5.Visible) textBox5.Visible = true;
  • 请尝试实施建议的解决方案之一,然后发布代码,我们将帮助您找到其他解决方案。由于您正在学习,因此您自己完成这些步骤非常重要和必要。相信我;)

标签: c# forms winforms


【解决方案1】:

这是您可以解决此问题的另一种方法。

美观紧凑:

private void button3_Click(object sender, EventArgs e)
{
    TextBox[] TBs = { textBox1, textBox2, textBox3, textBox4 };
    TextBox tb = TBs.Where(x => !x.Visible).FirstOrDefault();
    if (tb != null) { tb.Visible = true; }
}

【讨论】:

  • FirstOrDefault 带谓词,不需要Where
  • 你是对的,@Wyck,确实如此……但这样写对我来说总是显得“奇怪”。
【解决方案2】:

使用此代码:

 private void button3_Click(object sender, EventArgs e)
        {
            
            if (!textBox3.Visible)
            { textBox3.Visible = true; return; }
            if(!textBox4.Visible)
            { textBox4.Visible = true; return; }
            if (!textBox5.Visible)
            { textBox5.Visible = true; return; }
            if (!textBox6.Visible)
            { textBox6.Visible = true; return; }
        }

【讨论】:

  • 您的代码非常完美,但我建议使用嵌套的 if else 分支,而不是在 if 分支本身中返回函数
【解决方案3】:

我的评论示例:

public partial class Form1 : Form
{
    private List<TextBox> textBoxes;

    private int iterator = 0;

    public Form1()
    {
        InitializeComponent();

        this.textBoxes = new List<TextBox>
            {
                this.textBox1,
                this.textBox3,
                this.textBox2,
                this.textBox4
            };
        this.textBoxes.ForEach(tb => tb.Visible = false);
    }

    private void buton_Click(object sender, EventArgs e)
    {
        if (this.iterator >= this.textBoxes.Count())
        {
            // Do something that you need, then all textboxes are visible

            return;
        }

        this.textBoxes[this.iterator++].Visible = true;
    }
}

ctor 中,您可以通过控制textBoxes 中的顺序来控制显示textboxes 的顺序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    相关资源
    最近更新 更多