我有一个列表 UserControl
我想知道哪个 UserControl
正在调用事件 MouseEnter
. 我增加了多个 UserControl
在 TableLayoutPanel
.
List<MyUserControl> form = new List<MyUserControl>();
for (int x = 0; x < dt.Rows.Count; x++)
{
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200));
if (x == 0)
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
form.Add(new MyUserControl());
}
for (int x = 0; x < form.Count; x++)
{
form[x].MouseEnter += new EventHandler(Form_MouseEnter);
tableLayoutPanel1.Controls.Add(form[x], x, 0);
}
我怎样才能知道哪个 UserControl
激活了事件?
最大的不同是,如果你给你的新产品起了个名字,那么你的新产品就会有很大的不同。MyUserControl 因为默认的Name是一个空字符串。你能不能试着把你的代码改成这样,看看是否有帮助?
List<MyUserControl> form = new List<MyUserControl>();
for (int x = 0; x < 5; x++)
{
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200));
if (x == 0)
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// Here are the changes
MyUserControl myUserControl = new MyUserControl();
myUserControl.Name = "MyUserControl_" + x.ToString("D2"); // Name it! (Default is "")
myUserControl.MouseEnter += MyUserControl_MouseEnter; // Hook the MouseEnter here
myUserControl.Codigo = 1000 + x; // Example to set Codigo
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
form.Add(myUserControl); // NOTE! This is changed from 'new MyUserControl()'.
}
for (int x = 0; x < form.Count; x++)
{
tableLayoutPanel1.Controls.Add(form[x], x, 0);
}
现在处理程序看起来像这样。
private void MyUserControl_MouseEnter(object sender, EventArgs e)
{
MyUserControl myUserControl = (MyUserControl)sender;
Debug.WriteLine(
"MouseEnter Detected: " + myUserControl.Name +
" - Value of Codigo is: " + myUserControl.Codigo);
}
... 其中(根据你对Codigo的评论)... ...。
class MyUserControl : UserControl
{
public int Codigo
{
set
{
test = value;
}
get
{
return test;
}
}
int test = 0;
// Of course there is more implementation of MyUserControl that follows...
}
我真的希望这能帮助你解决你所遇到的问题。
this.panel1.MouseEnter += new System.EventHandler(this.panel1_MouseEnter);
使用 sender
private void panel1_MouseEnter(object sender, System.EventArgs e)
{
var userControl = sender as MyUserControl
}