TipVisor
TipVisor

Reputation: 1092

how to code to button event from new class?

I am create a simple code for learning c#. i create windows form and place button and label. i want to click button, open folder browse dialog box and select folder. after press ok , i want to show the folder path on the label. this work i know that work in button click event. but, i try to this code write in new class. and call to button click event. c# .Net framework 4.6

main form code

        static Folderbrowse folderbrowse = new Folderbrowse();

        private void btn_SelectFolder_Click(object sender, EventArgs e)
        {

        }

        private void lbl_SelectFolderPath_Click(object sender, EventArgs e)
        {

        }
    }
}




Form1 theform1 = new Form1();
static void Browsedialog()
{
    FolderBrowserDialog FBD = new FolderBrowserDialog();
    if (FBD.ShowDialog() == DialogResult.OK)
    {

    }
}

enter image description here

enter image description here enter image description here

Upvotes: 1

Views: 85

Answers (1)

Leon
Leon

Reputation: 483

You could make a helper-class and call a method that opens the folderBrowserDialog and returns the selected path:

using XY;
...
private HelperClass helper = new HelperClass();

private void btn_SelectFolder_Click(object sender, EventArgs e)
{
    lbl_SelectFolderPath.Text = helper.GetFolderPath();
}

And this would be your other class:

namespace XY
{
    public class HelperClass
    {
        public string GetFolderPath()
        {
            var openFolderDialog = new OpenFolderDialog();
            if(openFolderDialog.ShowDialog() == DialogResult.OK)
            {
                return openFolderDialog.SelectedPath;
            }   
            return string.Empty;
        }
    }
}

In this case you could also make the helper-class or the method static, because you dont refer to anything to the rest of your code.

Upvotes: 1

Related Questions