Mogli
Mogli

Reputation: 2012

How to show a panel dynamically on mouse enter event?

Like in web page using css we can show a div on mouse enter or hover, in the same way i want to show a panel on mouse enter event of a button, but i am unable to do this. I am trying like this.

private void btn2_MouseEnter(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        btn.BackColor = System.Drawing.Color.MistyRose; //this is executed on mouse enter
        Point locationOnForm = btn.FindForm().PointToClient(
        btn.Parent.PointToScreen(btn.Location));
        Panel pnl = new Panel();
        Label lbl = new Label(); 
        lbl.Text = "anything";
        pnl.Controls.Add(lbl);
        pnl.Location = new Point(locationOnForm.X, locationOnForm.Y);
        pnl.Size = new Size(500, 500);
        pnl.BackColor = Color.SkyBlue;
        pnl.Visible = true;
        pnl.Show();
    }

I am not getting how to solve this. I want to know that

1) Is this the right approach or there is any other way of doing this?

2) If this is ok then what is the mistake i am doing here ?

Thanks.

Upvotes: 0

Views: 437

Answers (2)

Arun
Arun

Reputation: 978

You have to add the panel to the Form controls

Form1.Controls.Add(pnl);

If you plan to have a panel hover over the button like a <div> in Web, you will have to call BringToFront() to ensure that the panel does not appear behind the button or other controls on the form -

pnl.BringToFront();

Also like the previous answer, it may be better to have a panel placed on the form already and just set visible to true or false as well as the panel location otherwise you may end up adding multiple panels to the Form controls.

If you plan on just showing plain text in the panel, it may be easier to use Tooltip control -

MSDN - Tooltip Control

Upvotes: 0

Nicolas Tyler
Nicolas Tyler

Reputation: 10552

Don't create the panel on mouse enter, rather have the panel created already then just show and hide it.

private void button1_MouseEnter(object sender, EventArgs e)
{
    panel1.Show();
}

Upvotes: 1

Related Questions