Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting multiple controls and changing propertys

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.

like image 325
ZeroByter Avatar asked Jan 19 '26 06:01

ZeroByter


1 Answers

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;
like image 66
Grant Winney Avatar answered Jan 20 '26 21:01

Grant Winney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!