Form2 から Form1 のコンボボックス項目をリロードしたいのですが、2 つのフォームがあります。Form1 を Form2 の MdiParent として次のように設定します。
Form2 f2 = new Form2();
f2.MdiParent = this;
f2.Show();
Form2 内から Form1 コントロールにアクセスするにはどうすればよいですか?
これを試して、
String nameComboBox = "nameComboBoxForm1"; //name of combobox in form1
ComboBox comboBoxForm1 = (ComboBox)f2.MdiParent.FindControl(nameComboBox);
次のようなプロパティを定義するForm1
必要があります。
Public ComboBox.ObjectCollection MyComboboxitems{
get{ return {the Combox's name}.Items}
}
次にForm2
、Load
イベント ハンドラーで次のようにします。
{name of form2 combobox}.Items = ((Form1)Me.MdiParent).MyComboboxitems;
これは、フォーム 1 でコンボボックスのすべてのプロパティを公開するのではなく、必要なものだけを公開するためです。
コード例の {...} を実際のオブジェクト名に置き換えます。
You can declare a public static List in Form1 and set it to the datasource of form1combobox as shown here.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.IsMdiContainer = true;
}
public static List<string> list;
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.MdiParent = this;
frm2.Show();
comboBox11.DataSource = list;
}
}
In the load event of form2, set the declared form1 list to refer to new instantiated list having the items of form2.combobox.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
List<string> list = new List<string> { "a", "b", "c" };
private void Form2_Load(object sender, EventArgs e)
{
comboBox1.DataSource = list;
Form1.list = list;
}
}