Search code examples
c#.netbackgroundlinklabelfileopendialog

Open File Dialog box on Clicking Link Label


I've created a log in panel in which I've used Transparent group box(with user name text box and password text box), and used a wallpaper on background, now I've Used a link label on this log in panel by clicking on which the user can change the background wallpaper of the log in panel.

Means when user clicks on the link label (lnklblChangeBackGround) with text "Click Here to Change Background" open dialogue box will open and user can select the Wallpaper from here and then by clicking on OK or Select the wallpaper will be assigned to background of the log in panel

Can any one help me out that

  1. how can i open a open dialogue box by clicking on the link label
  2. how can i assign a select wallpaper to the background of my log in panel

Note: I'm Creating this using VS 2010 using C#. and it's a desktop App and i'm using winform here.


Solution

  • At first you have to add an Event (LinkClicked) to your Link Label.


    Just place this code here to open a file dialog.

    private String getPicture()
    {
        string myPic = string.Empty;
    
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.Filter = "jpg (*.jpg)|*.jpg|png (*.png)|*.png";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
            myPic = openFileDialog1.FileName;
    
        return myPic;
    }
    

    You can edit the filter to avoid the user choosing images, which is not supported in your opinion.

    With this code below you can set the Background Image of your pictureBox

    private void setBackground(String picture)
    {
        pictureBox1.Image = null;
        pictureBox1.Image = Image.FromFile(picture);
    }
    

    And the final version would look like this

    private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        String myFile = getPicture();
        setBackground(myFile);
    }
    

    if this is too much code or too complicated for you, then you can just put it all in one function like this

    private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        string myPic = string.Empty;
    
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.Filter = "jpg (*.jpg)|*.jpg|png (*.png)|*.png";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
            myPic = openFileDialog1.FileName;
        pictureBox1.Image = null;
        pictureBox1.Image = Image.FromFile(myPic);
    }