Search code examples
c#methodsbuttonclick

Recycle Button Click Event c#


I want to recycle a Button click Event method in different parts of my application, I would change the filter of the file and the variable where to save the path to file. How could I refactor my code to reuse the method? I'm working with C#

    /// <summary>
    /// Click on the button "Examinar" and open a file explorer window and select the .ipr file.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e">Routed event arguments called E.</param>
    private void Button_Click_Examinar(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog
        {
            Filter = "Text files (*.ipr)|*.ipr"
        };
        if (openFileDialog.ShowDialog() == true)
        {
            iprPath = openFileDialog.FileName;
        }

        fileUploadBox.Text = iprPath;
    }

I need to change iprPath and Filter file type. Thanks!


Solution

  • You could move the logic to a separate method:

    private void ChoseFile(string filter, TextBox textBoxToUpdate)
    {
        string fileChosen = null;
        OpenFileDialog openFileDialog = new OpenFileDialog
        {
            Filter = filter
        };
        if (openFileDialog.ShowDialog() == true)
        {
            fileChosen = openFileDialog.FileName;
        }
    
        textBoxToUpdate.Text = fileChosen;
    }
    

    The method takes two arguments - a string with a filter for the OpenFileDialog, and a TextBox that will be updated once a file is chosen.

    Suppose you have three buttons, with three corresponding textboxes, you could then use the method like this:

    private void IprFileButton_OnClick(object sender, RoutedEventArgs e)
    {
       ChoseFile("Text files (*.ipr)|*.ipr", tbIprFile);
    }
    
    private void TextFileButton_OnClick(object sender, RoutedEventArgs e)
    {
        ChoseFile("Text files (*.txt)|*.txt", tbTextFile);
    }
    
    private void ImageFileButton_OnClick(object sender, RoutedEventArgs e)
    {
        ChoseFile("Image Files|*.jpg;*.jpeg;*.png;*.gif;*.tif", tbImageFile);
    }