user740327
user740327

Reputation: 31

Tool tip problem

I am trying to programmatically set a tooltip for a label (added at runtime) on a UserControl within a form. The button used to trigger the code is on the user control itself. The problem is that when I click the button the tooltip is not assigned. However if I use basically the same code on the parent form and put it behind a button on the parent form, I can assign a tooltip to a label on the parent form. Also if I add the label to user control prior to running it works as well.

The following code is from a button on the user control that sits on the main form.

   private void button1_Click(object sender, EventArgs e)
        {
            Label lblTest = new Label();
            lblTest.Text = "Test";
            ToolTip tt = new ToolTip();
            tt.SetToolTip(lblTest, "ToolTipTest");
            this.Controls.Add(lblTest);
            lblTest.Location = new Point(10, 10);
        }

Any help will be much appreciated.

Upvotes: 3

Views: 294

Answers (2)

Arun
Arun

Reputation: 2523

Most likely, the ToolTip object goes out of scope after the Click Event. Can you try declaring it outside your Click Event:

ToolTip tt = new ToolTip();
private void button1_Click(object sender, EventArgs e) 
{  
   // and so on...

Upvotes: 0

Alex Essilfie
Alex Essilfie

Reputation: 12613

You can try showing the tooltip manually. Use this code like this:

ToolTip tt = null;

private void button1_Click(object sender, EventArgs e)
{
    Label lblTest = new Label();
    lblTest.Text = "Test";
    tt = new ToolTip();
    this.Controls.Add(lblTest);
    lblTest.MouseHover += new EventHandler(label_Hover);
    lblTest.Location = new Point(10, 10);
}

private void label_Hover(object sender, EventArgs e)
{
    tt.Show((Label)sender, "Tooltip");
}

The code in bold are my additions and/or modifications.

Upvotes: 2

Related Questions