C# と VB.NET の質問掲示板

わんくま同盟

ASP.NET、C++/CLI、Java 何でもどうぞ

C# と VB.NET の入門サイト


(過去ログ 151 を表示中)
■87911 / )  C# フォーム間の変数受け渡し
□投稿者/ C#はじめました (1回)-(2018/07/12(Thu) 19:30:39)

分類:[C#] 

C# Windowsフォームアプリケーションで
Form1とForm2の2つのフォーム間で変数の共有化(受け渡し)を行いたいと思っています。

Form1にnumericUpDown1、button1を設けて、
button1を押すとForm2が開きます。

Form2にもnumericUpDown1、button1を設けてあり、
button2を押すとForm2が閉じて、Form2のnumericUpDown1の値が
Form1のnumericUpDown1の値に反映されます。

本当であればForm1のbutton1を押してForm2を開いたとき、
Form1のnumericUpDown1の値をForm2のnumericUpDown1の値に反映させたいのですが
下記のコードでは、それがうまくできません。

Form2のnumericUpDown1の値をForm1のnumeriUpDown1の値に反映はできているのですが、、、

どこがおかしいのか分かる方いたら、どのようにコードを直したらよいか教えて下さい。

宜しくお願い致します。

親フォームForm1.cs↓

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.ShowDialog();

            this.numericUpDown1.Value = form2.numericUpDown1.Value;
            form2.Dispose();
        }
    }
}

子フォームForm2.cs↓

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

namespace WindowsFormsApplication2
{
    public partial class Form2 : Form
    {
        Form1 form1 = new Form1();

        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            this.numericUpDown1.Value = form1.numericUpDown1.Value;
            Refresh();
        }
    }
}


返信 編集キー/


管理者用

- Child Tree -