Question

This is a pseudo-problem. I can force the link to open the desired page in the EventHandler, but I want to know what I am doing wrong in this scenario, and do it the right way:

In InitializeComponent(), in partial class Form1:

public void InitializeComponent()
{
    this.linkLabel1 = new System.Windows.Forms.LinkLabel();

    //...

    // 
    // linkLabel1
    // 
    this.linkLabel1.AutoSize = true;
    this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(0, 1);
    this.linkLabel1.LinkColor = System.Drawing.Color.Red;
    this.linkLabel1.Location = new System.Drawing.Point(259, 100);
    this.linkLabel1.Name = "linkLabel1";
    this.linkLabel1.Size = new System.Drawing.Size(13, 17);
    this.linkLabel1.TabIndex = 5;
    this.linkLabel1.TabStop = true;
    this.linkLabel1.Text = "?";

    /**/
    this.linkLabel1.Links.Add(1, 1, "www.google.com"); //This is the only code I have added manually.
    /**/

    this.linkLabel1.UseCompatibleTextRendering = true;
    this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkClicked);

}

//...

private System.Windows.Forms.LinkLabel linkLabel1;

The EventHandler, LinkClicked, in public partial class Form1 : Form:

private void LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
}

When you click linkLabel1, you get the classic "NullReferenceException: Object reference not set to an instance of an object" when you call System.Diag....

I haven't had much training on error-handling or vocab, so this might as well be Greek to me. The button is not static... should I create a... new instance of the link?

Didn't the program already create an instance? If not, why does .Size, .Name, .Text, etc work... but not .Links.Add? No idea what I'm talking about.

Was it helpful?

Solution 2

I believe that your problem is that you're adding the link in the auto-generated designer file. You can't predict when Visual Studio will modify/recreate it, and what changes it will have. In my case, the same statement you use gets replaced by:

this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(1, 1);

The workaround is simple enough. Place:

this.linkLabel1.Links.Add(1, 1, "www.google.com");

In the Load event of your form. Also make sure to remove from the designer region all the unwanted parts of the code which have been refactored by Visual Studio.

OTHER TIPS

The problem is probably in the e.Link.LinkData.ToString()

Check that LinkData is not null...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top