みなさんこんにちは!ひろぽんです!
今回はFormから別のFormに値を持って行ったり、今開いているFormから値を受け取ったりする為の実装についてみていきたいと思います!
[s_ad]
目次
パターン1:MainFormから別Formに値を渡す
まずはこんな感じのFormを2つ用意します。


でそれぞれ中のコードをこんな感じにします。
namespace BringValueWithForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var form = new SubForm(textBox1.Text);
form.ShowDialog();
}
}
}
namespace BringValueWithForm.Pattern1
{
public partial class SubForm : Form
{
private string _str;
public SubForm(string str)
{
InitializeComponent();
_str = str;
}
private void SubForm_Load(object sender, EventArgs e)
{
label1.Text = $@"MainFormから{_str}の値が来ました。";
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
これを実行するとこんな感じ!


ちゃんと値がわたっている!!
パターン2:MainFormで別Formから値をもらう
で次はパターン2。
今回はMainFormから開いたSubFormで何かしらの入力がされて、その値をMainFormで受け取るというもの。


こんな感じでパターン1とは反対のFormを用意する。
中身はこんな感じ。
namespace BringValueWithForm.Pattern2
{
public partial class MainForm2 : Form
{
public MainForm2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var form = new SubForm2();
form.ShowDialog();
// ここでform1が閉じられたら
label1.Text = $@"SubFormから{form.TextBox1Str}の値が渡ってきました。";
}
}
}
namespace BringValueWithForm.Pattern2
{
public partial class SubForm2 : Form
{
public string TextBox1Str { get; private set; } = "";
public SubForm2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TextBox1Str = textBox1.Text;
this.Close();
}
}
}
これを実行するとこんな感じ

立ち上げ時はただのlabelだが。

SubFormでtestと入力されてからSubFormが閉じられると。

こんな感じで値が渡った!
[s_ad]
GitHubでソースを公開しています!
下記リポジトリのBringValueWithFormというフォルダで、今回のソースを公開しています!
リポジトリの詳細は下記を参照ください!
あわせて読みたい


GitHubリポジトリについて
【このブログで紹介しているコードをまとめてアップしています】 下記リポジトリで、このブログで紹介している全てのコードを公開しています。 是非ローカルにクローン...
コメント