在 C# 中隐藏另一个窗体的标签页

hide tabpages from another form in c#

我有一个登录表单和另一个表单。当用户为 x 且密码为 y 时,我想完全显示表单,这部分我没有问题,但是当用户 z 通过 t 登录时,我希望他无法显示 3 个标签页中的 2 个。总之,如果您能告诉我如何从另一个表单中隐藏一个表单的标签页,我将不胜感激。

 private void button1_Click(object sender, EventArgs e)
    {
        if (textBox1.Text == "x" && textBox2.Text == "123")
        {
            this.Hide();
            Form1 fr1 = new Form1();
            fr1.ShowDialog();

        }
        else
        {
            if (textBox1.Text == "z" && textBox2.Text == "t")
            {
                this.Hide();
                Form1 fr1 = new Form1();
               //how can I hide 2 out of 3 tabpages on form1(fr1) for this user
                fr1.ShowDialog();




            }
         }

I would be so appreciate if you could say me how to hide a tab page of a form from another form.

听起来您需要一种将信息从一个 Form 传递到另一个的方法。通常这可以通过 Form 构造函数来实现,这样在实例化时就会出现有关如何显示特定控件的相关信息。如果出于某种原因,使用构造函数方法并不理想——您可以使用共享机制来存储和收集相关数据。通常覆盖 OnLoad 是进行调用以收集所述数据的不错选择。

获得所需数据后,即可使用它来显示或隐藏标签页。我通常建议 data binding and using an MVVM pattern 用于 WinForms。

例如,您可以有一个模型来表示登录用户的各种详细信息,然后绑定到各种控件属性。

正如我所提到的,您需要一种方法来将可见性从其构造函数传达给 Form1。所以将其添加到构造函数中:

private bool _hideTwoOutOfThreeTabs;

public Form1(bool hideTwoOutOfThreeTabs = false)
{
    _hideTwoOutOfThreeTabs = hideTwoOutOfThreeTabs;
}

然后像这样覆盖 OnLoad

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    if (_hideTwoOutOfThreeTabs)
    {
        foreach (var tabPage in tabControl1.TabPages.Cast<TabPage>())
        {
            // TODO: Some logical test to ensure this is the desired tab control to hide
            // if (tabPage)
            {
                tabPage.Visible = false;
            }
        }
    }
}

最终您的方法将如下所示:

private void button1_Click(object sender, EventArgs e)
{
    var textOne = textBox1.Text,
        textTwo = textBox2.Text;

    if (textOne == "x" && textTwo == "123")
    {
        Hide();
        using(var fr1 = new Form1())
        {
            fr1.ShowDialog();
        }
    }
    else if (textOne == "z" && textTwo == "t")
    {
        Hide();
        using(var fr1 = new Form1(true))
        {
            fr1.ShowDialog();
        }
    }
}