簡體   English   中英

C#WindowsForms-在Visual Studio上將文本框從Form1發送到Form2

[英]C# WindowsForms - Send textbox from form1 to form2 on visual studio

我在Visual Studio上有2種表單,

form1 have textbox1.text
form2, have textbox2.text and btnSave

obs:當我單擊表單1上的另一個按鈕時,form2打開:

Form new = new form2();
           nova.Show();

如何單擊btnSave將textbox2內容從form2發送到form1(textbox1)? 在此單擊按鈕事件內,將需要什么代碼。

謝謝

請嘗試以下操作:步驟1:為form2類創建一個構造函數,如下所示:

 public Form2(string strTextBox)
        {
            InitializeComponent();
            label1.Text = strTextBox;
        }

步驟2:在form1的按鈕單擊事件處理程序中實例化form2類,如下所示:

 private void button1_Click(object sender, EventArgs e)
        {
            Form2 obj1 = new Form2(textBox1.Text);
            obj1.Show();
            this.Hide();
        }

在第二個表單上創建一個事件,該事件可以在保存表單時觸發:

public event Action Saved;

然后在該表單上創建一個屬性,該屬性允許訪問文本框的文本:

public string SomeTextValue //TODO: rename to meaningful name
    { get{ return textbox2.Text;} }

然后,您需要在Saved表單時觸發Saved事件:

if(Saved != null)
    Saved();

然后,當您第一次在Form1創建表單時,將事件處理程序附加到該事件:

Form2 child = new Form2();
child.Saved += () => textbox1.Text = child.SomeTextValue;
child.Show();

請注意,如果在保存時也要關閉第二個窗體,則不需要自定義事件,您可以直接使用FormClosing

研究我能夠使它工作,浪費了一些時間,但現在一切都很完美,這是對我有用的代碼:

在form2上:

public partial class form2 : Form
    {
        private string nome;
        public string passvalue
        {
            get { return nome; }
            set { nome = value; }
        }

form2,按鈕保存:

private void btnSalvar_Click(object sender, EventArgs e)
        {
            passvalue = txtMetragemcubica.Text;
            this.Hide();
        }

在form1上(此按鈕打開form2):

private void btnMetragemcubica_Click(object sender, EventArgs e)
        {
            form2 n = new form2();
            n.ShowDialog();
            txtMetragem.Text = n.passvalue
        }

現在,它以這種方式工作:在窗體1上打開,然后單擊btnMetragemcubica按鈕並打開form2,然后在不同的文本框中插入值,並在txtMetragemcubica上生成結果,當我單擊保存按鈕(btnSalvar)時,它將關閉form2並將值發送給txtMetragem文本框中的form1。

在這里工作完美,希望也能幫助別人。 無論如何感謝所有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM