[英]How do I access controls in a custom user control in a flow layout panel?
我在ac#表单应用程序中创建了一个自定义用户控件,其中包含一个组框,一个复选框和一个按钮。
在主应用程序中,我可以将这些控件添加到流布局面板中并设置其初始值。
问题是,在项目已位于流布局面板中之后,如何访问按钮事件和复选框?
private void btnAdd_Click(object sender, EventArgs e)
{
AttributeListItem.AttributeListItem at = new AttributeListItem.AttributeListItem();
at.groupbox.Text = lbxLDAPFields.GetItemText(lbxLDAPFields.SelectedItem);
flPanel.Controls.Add(at);
// button name is btnEdit
}
使用事件和公共属性,因为这听起来像您在设计器中添加了每个项目,所以您可以连接事件处理程序,并在用户控件中访问为其分配名称的属性,以便以后查找。 这是一个非常粗糙的示例,它会为您工作。
用户控件
public partial class MyCustomUserControl : UserControl
{
public event EventHandler<EventArgs> MyCustomClickEvent;
public MyCustomUserControl()
{
InitializeComponent();
}
public bool CheckBoxValue
{
get { return checkBox1.Checked;}
set { checkBox1.Checked = value; }
}
public string SetCaption
{
get { return groupBox1.Text;}
set { groupBox1.Text = value;}
}
private void button1_Click(object sender, EventArgs e)
{
MyCustomClickEvent(this, e);
}
}
Form1中
public partial class Form1 : Form
{
int count =1;
public Form1()
{
InitializeComponent();
}
private void mcc_MyCustomClickEvent(object sender, EventArgs e)
{
((MyCustomUserControl)sender).CheckBoxValue = !((MyCustomUserControl)sender).CheckBoxValue;
}
private void button1_Click(object sender, EventArgs e)
{
MyCustomUserControl mcc = new MyCustomUserControl();
mcc.MyCustomClickEvent+=mcc_MyCustomClickEvent;
mcc.Name = "mmc" + count.ToString();
mcc.SetCaption = "Your Text Here";
flowLayoutPanel1.Controls.Add(mcc);
count += 1;
}
private void button2_Click(object sender, EventArgs e)
{
var temp = this.Controls.Find("mmc1", true);
if (temp.Length != 0)
{
var uc = (MyCustomUserControl)temp[0];
uc.SetCaption = "Found Me";
}
}
}
肮脏而简单的解决方案:公开UserControl
控件
然后你可以做类似的事情
userControl1.button1.PerformClick();
PS:顺便说一句,您已经在示例中访问了groupbox
,因此您似乎对此有所了解。 您是否以编程方式创建控件(也许在用户控件构造函数中)? 然后,可以将FlowLayoutPanel
公开,并使用其Control
集合来查找所需的控件,或者可以将控件实例保留在UserControl
的公共字段/属性中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.