简体   繁体   English

单击按钮更改其他表单中的文本

[英]Changing text in another form by clicking a button

I've been trying to change the text of a textbox in Form1 by clicking a button (button1 in form2 is "STARTA") in Form2 and probably spent a good 2 hours now (I'm a programming-newbie!). 我一直在尝试通过单击Form2中的按钮(form2中的button1是“STARTA”)来更改Form1中文本框的文本,现在可能花了2个小时(我是编程新手!)。 I have been searching around for similiar questions and found a bunch, but even after trying a lot of them I can't get it to work. 我一直在寻找类似的问题,并找到了一堆,但即使尝试了很多,我也无法让它工作。

Form1[DESIGN] Form1的[设计]

在此输入图像描述

Form2[DESIGN] 窗体2 [设计]

在此输入图像描述

The method I'm trying right now is something I found here 我现在正在尝试的方法是我在这里找到的

In Form1 I wrote this: 在Form1中我写了这个:

public string STARTTID
{
    get
    {
        return this.textBox3.Text;
    }
    set
    {
        this.textBox3.Text = value;
    }
}

I know it doesn't quite make sense to get and set an empty textBox, but I've tried so many different solutions which I think should work, but the textBox's text just wont change when I click the button! 我知道获取并设置一个空的textBox并没有多大意义,但我已经尝试了许多不同的解决方案,我认为应该可行,但是当我点击按钮时,textBox的文本不会改变! In form2, when button1 is clicked, I wrote this: 在form2中,当点击button1时,我写道:

string TIDEN = DateTime.Now.ToString("HH:mm:ss tt");
Form1 first = new Form1();
first.STARTTID = TIDEN;

What I'm trying to do, is that I want the text in textBox3 in form1 to change to the current time when button1 in form2 is pressed. 我想要做的是,我希望form1中textBox3中的文本更改为按下form2中的button1时的当前时间。

Sorry if this post is a bit messy, it's my first and english isn't my strongest language. 对不起,如果这篇文章有点乱,那是我的第一篇,英语不是我最强的语言。

problem is you creating new Form1 and update label on that one, not in the your initial form 问题是你在那个上创建新的Form1并更新标签,而不是在你的初始形式

    Form1 first = new Form1();
    first.STARTTID = TIDEN;

You don't need to create new form because you already created it. 您不需要创建新表单,因为您已经创建了它。 what you can do is parse the Form1 to Form2 when you create Form2 by using constructor which accept Form as parameter. 当你使用接受Form作为参数的构造函数创建Form2时,你可以做的是解析Form1到Form2。 or create property in Form2 for Form1 and set that when you creating Form2. 或者在Form2中为Form1创建属性,并在创建Form2时进行设置。

Form1 Form1中

Form2 f2 = new Form2(this);
f2.Show();

Form2 窗体2

public partial class Form2 : Form
{
    private Form1 form1;

    public Form2(Form1 form1)
    {
        InitializeComponent();
        this.form1 = form1;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        form1.STARTTID = "set by form2";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM