1

I'm creating a user control in C# but I can't figure out how to do the event stuff. I want to change the backcolor property of the panel on mouse hover but it's not working.

Code:

public partial class QuestionList : UserControl
{
    public QuestionList()
    {
        InitializeComponent();
    }

    public struct QuestionListItem
    {
        public string Question { get; set; }
        public string Answer { get; set; }

        public QuestionListItem(string question, string answer)
        {
            Question = question;
            Answer = answer;
        }
    }

    public void Add(QuestionListItem questionlistItem)
    {
        Panel panel = new Panel();
        panel.Dock = DockStyle.Top;

        Label label = new Label();
        label.MouseHover += Label_MouseHover;
        label.Dock = DockStyle.Fill;
        label.Text = questionlistItem.Question;
        panel.Controls.Add(label);

        Controls.Add(panel);
    }

    //Here (no idea what I just did..)
    private void Label_MouseHover(Object sender, EventArgs e)
    {
        Label label = (Label)sender;
        Panel panel = (Panel)label.Container;
        panel.BackColor = Color.Red;
    }
}

1 Answer 1

1

I think you have added your event handler right. The problem is with the line you put in your event handler:

Panel panel = (Panel)label.Container;

Should be

Panel panel = (Panel)label.Parent;

Change the Container into Parent.

Also, I think it is best to use VS designer to test what is the strongly-typed signature of the event handler. In your signature, you use EventArgs. I believe it should be MouseEventArgs instead.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh my god thank you it works !! Have a great day :DD
Oh it's youu. I didn't check on my older thread until now, upvoted for the good logical answer. Thanks for the instant and useful help you give, you're a good person :))
@Tayab no problem. ^_^ thanks! that will save my day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.