我有一个User Control
.现在我想限制用户只能使用一个 每个表单User Control
。
假设我的自定义控件是文本框。在这种情况下,用户每个表单只能使用一个文本框。
试试 Enterevent
this.TxtBox.Enter += new System.EventHandler(this.TxtBox_Enter);
private void TxtBox_Enter(object sender, EventArgs e)
{
//disable all other textboxes
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
c.Enabled = false;
}
}
}
如果要限制用户在单个窗体上具有多个控件实例,请使用以下技巧来限制
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
this.Load += new System.EventHandler(this.UserControl1_Load);
}
private void UserControl1_Load(object sender, EventArgs e)
{
if (this.ParentForm.Controls.OfType<UserControl1>().Count() > 1)
{
//form already has a controler throw error
throw new System.Exception("you can have only one instance of me on a single form");
this.Enabled = false;
this.Dispose();
}
}
}