从另一个表格重新加载组合框项目
问题描述:
我有两种形式,我想从Form2重新加载Form1中的组合框项目。 我将Form 1的窗体2的的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
,你需要像这样定义一个属性:在Load
事件处理程序上Form2
Public ComboBox.ObjectCollection MyComboboxitems{
get{ return {the Combox's name}.Items}
}
然后:
{name of form2 combobox}.Items = ((Form1)Me.MdiParent).MyComboboxitems;
这是不要公开表单上的组合框的所有属性,只是t他是你想要的。
在代码示例中将{...}替换为实际的对象名称。
答
您可以在Form1中声明一个公共静态列表,并将其设置为form1combobox的数据源,如下所示。
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;
}
}
在form2的加载事件中,将声明的form1列表设置为引用具有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;
}
}
答
试试这个:在窗口2类
Form1 f1 = (Form1)Application.OpenForms["Form1"];
ComboBox cb = (ComboBox)f1.Controls["comboBox1"];
cb.Items.Clear();
cb.Items.Add("Testing1");
cb.Items.Add("Testing2");
:'((Form 1中)this.MdiParent).Combobox' – AbZy 2013-03-07 13:12:39
退房这个问题:http://stackoverflow.com/questions/8566/最好的方式来访问一个在另一个窗体中的控件 – 2013-03-07 13:12:50
@defaultlocale该问题没有任何可接受的答案 – Ehsan 2013-03-07 13:22:19