Home > Enterprise >  Refactor browse file methods to one method
Refactor browse file methods to one method

Time:01-19

Hi I have several browse methods for parameters which only differs in which setting and which textbox is used. Can i create a lambda or generic method or something to have only one implementation in C#?

    private void buttonBrowseSrcXML_Click(object sender, EventArgs e) {
        OpenFileDialog fileDialog = new OpenFileDialog();

        try {
            fileDialog.InitialDirectory = Path.GetDirectoryName(Settings.Default.XML_Original_File);
        } catch (ArgumentException) { }

        if (fileDialog.ShowDialog() == DialogResult.OK) {
            Settings.Default.XML_Original_File = fileDialog.FileName;
            Settings.Default.Save();
            textBoxSrcXML.Text = fileDialog.FileName;
        }
    }

CodePudding user response:

yes, you can move this code into a common method and then pass the setting and textbox to this method and call in each of your methods like the one below.

BrowseFile("XML_Original_File", textBoxSrcXML);

you will need to use these values accordingly in this method.

the method's signature should be something like private void BrowseFile(string settingName, TextBox textbox)

CodePudding user response:

The trick was the [] for settings indexing

    private void BrowseForStringSettingsFile(System.Windows.Forms.TextBox textBox, string settingKey) {
        OpenFileDialog fileDialog = new OpenFileDialog();

        try {
            fileDialog.InitialDirectory = Path.GetDirectoryName((string) Settings.Default[settingKey]);
        } catch (ArgumentException) { }

        if (fileDialog.ShowDialog() == DialogResult.OK) {
            Settings.Default[settingKey] = fileDialog.FileName;
            Settings.Default.Save();
            textBox.Text = fileDialog.FileName;
        }
    }
  • Related