c# winform窗體間的傳值


說明:本文講解兩個窗體之間的傳值,主要用到兩個窗體,form1,form2

1、在form1窗體單擊按鈕,打開窗體form2,然后把form2中文本框的值傳遞給form1

form1中的代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FormToform
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //獲取值
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 fr = new Form2();
            DialogResult rsult = fr.ShowDialog();
            if(rsult==DialogResult.OK)
            {
                //獲取窗體2傳回來的值
                listBox1.Items.Add(fr.UKind);
                listBox1.Items.Add(fr.UName);
            }
        }
    }
}
窗體form2的代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FormToform
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        //給窗體定義兩個屬性
     
        public string UKind {
            get { return textBox1.Text; }
            set { textBox1.Text= value; }
        }   
        public string UName
        {
            get { return textBox2.Text; }
            set { textBox2.Text = value; }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }
    }
}
2、在form1窗體單擊按鈕,打開窗體form2,然后給form2中文本框賦值

form1中按鈕的代碼如下:

  private void button2_Click(object sender, EventArgs e)
        {
            Form2 fr = new Form2();
            fr.UName = "姓名";
            fr.UKind = "類別";
            DialogResult rsult = fr.ShowDialog();
           
        }

 

form2與標題1一樣這里不做贅述

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM