1. 程式人生 > >c#父窗體子窗體之間傳值

c#父窗體子窗體之間傳值

c#窗體傳值

1. 父窗體向子窗體傳值

父窗體Form1程式

//使其成為主窗體Form1的一個屬性,
        private string text;
        public string Text
        {
            get { return text; }
            set { text = value; }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            text = "rfeg";
            Form2 fmChild = new
Form2(); fmChild.ShowDialog(this); }

子窗體Form2程式

//Form1向Form2傳值
        private void Form2_Load(object sender, EventArgs e)
        {
            Form1 fmMain;
            fmMain = (Form1)this.Owner;
            textBox1.Text = fmMain.Text;
        }

2. 子窗體向父窗體傳值

父窗體Form1程式

//使其成為主窗體Form1的一個屬性,
        private void button1_Click(object sender, EventArgs e)
        {
            text = "rfeg";
            Form2 fmChild = new Form2();
            fmChild.ShowDialog(this);
             if (fmChild.DialogResult == DialogResult.OK)
            {
                textBox1.Text =  fmChild.Path;

            }
            else
if (fmChild.DialogResult == DialogResult.Cancel) { textBox1.Text = "form was canceled"; } fmChild.Close(); }

子窗體Form2程式

        public string Path
        {
            get { return 瀏覽框.Text; }
            set { 瀏覽框.Text = value; }
        }
         private void button2_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                瀏覽框.Text = folderBrowserDialog1.SelectedPath;
            }
        }