2

我无法在 stackoverflow 上找到答案,所以就到这里了。单击子表单上的按钮时,我试图更改 MenuStrip 子项的文本。下面是来自我的子表单上的提交按钮的代码。单击时,它应该将“登录”的文本更改为“注销”。代码看起来很好,没有错误,但没有更新文本。

public AccessForm()
{
    InitializeComponent();
}

private void btnSubmit_Click(object sender, EventArgs e)
{
    try
    {
        if (txtUser.Text == "admin" && txtPass.Text == "1234")
        {
            MessageBox.Show("Access granted.", "Access");

            playgroundPlannersForm mainForm = new playgroundPlannersForm();

            mainForm.logInToolStripMenuItem.Text = "Log Out";
            this.Close();

        }
        else
        {
            MessageBox.Show("Incorrect Username or Password.", "Warning");
            txtUser.Clear();
            txtPass.Clear();
            txtUser.Focus();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Message: " + ex, "Error");
    }
}

private void btnCancel_Click(object sender, EventArgs e)
{
    this.Close();
}
4

1 回答 1

1

您正在创建主窗体的新实例并对其进行更改;您需要传递对原始表单的引用并使用它来更新它。

这是一种方法。在您的子表单中.. 添加此属性:

public playgroundPlannersForm ParentForm { get; set; }

..然后,在你上面的代码中,使用这个:

MessageBox.Show("Access granted.", "Access");

//playgroundPlannersForm mainForm = new playgroundPlannersForm(); <--- not needed anymore

ParentForm.logInToolStripMenuItem.Text = "Log Out";

在您的主表单中,在您显示您的子表单之前..执行以下操作:

SubForm subform = new SubForm();
subform.ParentForm = this;
subform.Show();

这会将父级设置为创建它的表单(根据您的代码,这是正确的表单)。您可能还需要进入表单设计器代码并将 loginToolStripMenuItem 公开(如果尚未公开)。

于 2012-11-14T00:21:56.663 回答