C# write text to textbox which adds written text to linklabel and when linklabel clicked goes to url?

StackOverflow https://stackoverflow.com/questions/21725228

  •  10-10-2022
  •  | 
  •  

Pregunta

I'm trying to do the following: I write link to textbox and it displays in a linklabel and after I click linklabel it goes to that url written in it? Everything goes well but pressing linklabel doesn't go to url.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        label2.Text = textBox1.Text;
        linkLabel1.Text = textBox2.Text;
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        Properties.Settings.Default.checkbox = checkBox1.Checked;
        Properties.Settings.Default.textbox = textBox1.Text;
        Properties.Settings.Default.label = label2.Text;
        Properties.Settings.Default.linkLabel = linkLabel1.Text;
        Properties.Settings.Default.Save();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        checkBox1.Checked = Properties.Settings.Default.checkbox;
        textBox1.Text = Properties.Settings.Default.textbox;
        label2.Text = Properties.Settings.Default.label;
        linkLabel1.Text = Properties.Settings.Default.linkLabel;        
    }

    private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
    }
¿Fue útil?

Solución

You have to start a process with the text of the LinkLabel, which should be a valid URL. This code will open the URL in the default browser:

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    Process.Start(linkLabel1.Text);
}

More info on the Process Class.

If the default browser is IE and you want to open it in Chrome for example you'll have to provide the necessary info:

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    Process p = new Process();
    p.StartInfo.FileName = @"C:\Users\<UserName>\AppData\Local\Google\Chrome\chrome.exe";
    p.StartInfo.Arguments = linkLabel1.Text;
    p.Start();
}

Of course you'll have to do validation to check if the text of the LinkLabel is a valid URL.

Otros consejos

You should use following code to add a link to LinkLabel as:

    // Add a link to the LinkLabel.
    LinkLabel.Link link = new LinkLabel.Link();
    link.LinkData = textbox2.Text;
    linkLabel1.Links.Add(link);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top