【问题标题】:How to change the Text of a Button in One form with a Button click of another Form?如何通过单击另一个表单的按钮来更改一个表单中按钮的文本?
【发布时间】:2015-12-28 07:35:47
【问题描述】:

我有两个表格。在第一种形式中,有一个带有“登录”文本的按钮。通过单击此按钮,我将打开另一个表单,我可以在其中使用用户名和密码登录。然后有一个按钮“继续”,它将验证用户名和密码,然后关闭第二个表单。然后它将第一个表单中“登录”按钮的文本更改为“欢迎,”+用户名。

一切正常,但我无法更改第一种形式的 按钮 的文本。我了解我需要在关闭 Form2 后刷新 Form1。但我做不到。

【问题讨论】:

  • “但我无法更改第一种形式的按钮文本”。这是因为您无法从 form2 访问 form1 的按钮吗?完成form2并返回form1后,您可以更改它,不是吗?
  • 是的,我无法从 form2 访问该按钮。我想在关闭 form2 后立即显示用户名。如果我在返回form1后更改它,那么我需要使用另一个按钮或单击什么的,对吧?

标签: c# winforms


【解决方案1】:

我会这样做,我在form2 上有一些东西,它记录了我输入的文本。

public partial class Form2 : Form {
    public string InputText = ""; //use this to record whatever is inputed in the Form2 by the user
    //somewhere else in the code
    public void foo(){ //this may be closing event or button pressed event
        InputText = textBoxInForm2.Text; //record the input from `form2` textbox
        this.DialogResult = DialogResult.OK; //mark as ok
    }

    //This is exactly the foo above, but just in case you wonder how the event FormClosing look like:
    //Add this event handler on your Form2
    private void Form2_FormClosing(object sender, FormClosingEventArgs e) {
        InputText = textBoxInForm2.Text; //record the input from `form2` textbox
        this.DialogResult = System.Windows.Forms.DialogResult.OK;
    }
}

然后在您的form1 中,您可以使用ShowDialog 打开form2。然后,如果对话框以您想要的方式产生,如下所示:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        Form2 form2 = new Form2(); //this must be declared in form1
        if (form2.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
            textBoxInForm1.Text = form2.InputText; //grab the input text
        }
    }
}

然后用form2中的任何值更新textBoxInForm1

编辑:在我给出的示例中,form2 是在 form1 构造中创建的。这显然可能并不总是正确的。但是示例显示强调form2 必须在form1 域内才能访问。在这种情况下,作为在其constructor 中声明的对象。您可以根据需要将form2 创建位置:作为Form1 类的property,在Form1 方法之一中,等等

【讨论】:

  • 让我试一试,如果这有助于我的目的,我会告诉你。不过感谢您的帮助。
  • form1的if条件应该写在哪里?里面有方法吗?
  • 是的,一种方法是在您调用Form2 的方法中。这是因为form2.ShowDialog 将阻止您的应用程序,直到您从form2 生成对话框结果。 DialogResult 应该通过关闭表单(如我的示例所示)或通过表单 2 中的确认方法(例如按下按钮)来生成。
  • 工作就像一个魅力!谢谢。
  • 太棒了!很高兴知道那件事! ;) 这里的想法是拥有一个公共变量并从父表单(form1)声明子表单(form2)。这样,form1 可以很容易地得到 form2 中的内容。我展示的并不是唯一的方式……这只是我的首选方式。 =)
【解决方案2】:

没有必要在你的form1中返回。

您应该创建另一个表单类并根据您的要求进行设计。 然后激活此表单以完成您的任务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-26
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    相关资源
    最近更新 更多