问题
I have a list of UserControl
and I want to know which UserControl
is calling event MouseEnter
. I add multiple UserControl
s on 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);
}
How do I find out which UserControl
activated the event?
回答1:
The thing that should make the biggest difference is if you give a Name to your new MyUserControl because the default Name is an empty string. Could you try changing your code to this and see if it helps?
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);
}
Now the handler looks like this:
private void MyUserControl_MouseEnter(object sender, EventArgs e)
{
MyUserControl myUserControl = (MyUserControl)sender;
Debug.WriteLine(
"MouseEnter Detected: " + myUserControl.Name +
" - Value of Codigo is: " + myUserControl.Codigo);
}
... where (based on your comment about 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...
}
I really hope this helps you fix the problem you're having.
回答2:
see in docmation
this.panel1.MouseEnter += new System.EventHandler(this.panel1_MouseEnter);
use the sender
private void panel1_MouseEnter(object sender, System.EventArgs e)
{
var userControl = sender as MyUserControl
}
来源:https://stackoverflow.com/questions/62152103/which-usercontrols-calling-event-mouseenter