好的,所以我的请求解释起来有点复杂。我有一个按钮,点击时会执行以下操作:
peopleNum = 0;
topPosition = 10;
public void submitStudent(string name)
{
peopleNum++;
topPosition += 25;
ComboBox people_comboBox = new ComboBox();
people_comboBox.Name = "people_comboBox" + peopleNum;
//ComboBox people_label_finder = this.Controls.Find("people_comboBox" + peopleNum, true).FirstOrDefault as ComboBox;
people_comboBox.Left = 150;
people_comboBox.Top = topPosition;
string[] people_comboBox_itemList = new string[3];
people_comboBox_itemList[0] = "Present";
people_comboBox_itemList[1] = "Late";
people_comboBox_itemList[2] = "Absent";
people_comboBox.DataSource = people_comboBox_itemList;
people_comboBox.MouseEnter += new EventHandler(people_comboBox_enter);
people_comboBox.MouseLeave += new EventHandler(people_comboBox_leave);
this.Controls.Add(people_comboBox);
}
然后对于“people_comboBox_enter”和“people_comboBox_leave”的功能,这里是代码:
private void people_comboBox_enter(object sender, EventArgs e)
{
ComboBox people_comboBox = this.Controls["people_comboBox" + peopleNum] as ComboBox;
if (people_comboBox != null)
{
people_comboBox.BackColor = Color.Red;
}
}
private void people_comboBox_leave(object sender, EventArgs e)
{
ComboBox people_comboBox = this.Controls["people_comboBox" + peopleNum] as ComboBox;
if (people_comboBox != null)
{
people_comboBox.BackColor = Color.White;
}
}
我想要发生的是,当鼠标在组合框上方时,它将变为红色,当鼠标离开时,它将变回白色。结果实际上是,当鼠标悬停在任何一个组合框上时(当有多个组合框时)只有最后一个组合框被更改。我怎么能做到这一点?非常感谢你。
答案 0 :(得分:4)
不要使用this.Controls
。触发事件的控件已在sender
。
在“输入”和“离开”事件中尝试此操作:
var people_comboBox = sender as ComboBox;
使用您当前的方法,每次单击peopleNum
按钮时submitStudent
都会递增。因此,如果您单击它3次,则基本上每次都运行此代码:
ComboBox people_comboBox = this.Controls["people_comboBox2"] as ComboBox;