[英]C# VSTO Winform Control Access controls from dynamically created Form
I have an Excel Addin that call a Windows Form that has a List Box. 我有一个Excel插件,该插件调用具有列表框的Windows窗体。 Before I show the form, I want to populate the ListBox
dynamically based on values from Excel . 在显示表单之前,我想基于Excel的值动态填充ListBox
。
Winform Looks like below: Winform如下所示:
Button click within Ribbon looks like below: 功能区中的按钮单击如下所示:
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Form1 fm = new Form1();
System.Windows.Forms.ListBox lbx = fm.Controls.Find("listBox1", true).FirstOrDefault() as System.Windows.Forms.ListBox;
lbx.Items.AddRange(new object[] { 1, 2, 3, 4, 5 });
fm.Show();
}
Is 是
System.Windows.Forms.ListBox lbx = fm.Controls.Find("listBox1", true).FirstOrDefault() as System.Windows.Forms.ListBox;
the best way of accessing the ListBox
and adding Item
s to it? 访问ListBox
并向其中添加Item
的最佳方法?
Or is there any other way? 还是还有其他方法?
In your scenario, since you create a new Form1 instance each time you wish to show it, and since it is a custom form, I would simply modify the form's constructor to accept the input data. 在您的方案中,由于每次创建新Form1实例时都希望创建它,并且它是自定义窗体,因此我只需修改窗体的构造函数以接受输入数据即可。
public Form1(object[] ListBoxData)
{
...
listBox1.Items.AddRange(ListBoxData);
}
You can then simply just pass in the values when you click the button; 然后,您只需在单击按钮时传递值即可。
Form1 fm = new Form1(new object[] { 1, 2, 3, 4, 5 });
fm.Show();
Per Chetan's suggestion: Property : Per Chetan的建议:属性:
public object[] ListBoxData
{
set
{
listBox1.Items.AddRange(value);
}
}
Change in Button Click: 按钮更改单击:
Form1 fm = new Form1();
fm.ListBoxData = new object[] { 1, 2, 3, 4, 5 };
fm.Show();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.