Question

Ok so my request is a bit complicated to explain. I have a button that does the following when clicked:

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);
    }

and then for the functions of "people_comboBox_enter" and "people_comboBox_leave" here is the code:

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;
            }
        }

What I want to happen is that so when the mouse is over a comboBox, it will turn Red and when the mouse leaves it will turn back white. What the result actually is, that when the mouse is over any of the comboBoxs (when there are multiple) only the last one gets changed. How can I accomplish this? Thank you very much.

Was it helpful?

Solution

Don't bother using this.Controls. The control that fired the event is already in sender.

Try this in your "enter" and "leave" events:

var people_comboBox = sender as ComboBox;

With your current approach, peopleNum is incremented each time you click the submitStudent button. So if you click it 3 times, you're basically running this code every time:

ComboBox people_comboBox = this.Controls["people_comboBox2"] as ComboBox;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top