Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing OpenFileDialog

I have 2 textboxes and 2 button [...] next to each textbox. Is it possible to use one OpenFileDialog and pass the FilePath to the respective textbox, based on which button is clicked? i.e...if I click buttton one and laod the dialog, when I click open on the dialog, it passes the fileName to the first textbox.

like image 616
Saif Khan Avatar asked Jul 06 '26 13:07

Saif Khan


1 Answers

Whenever you think "there's common functionality!" you should consider a method to implement it. It could look like this:

    private void openFile(TextBox box) {
        if (openFileDialog1.ShowDialog(this) == DialogResult.OK) {
            box.Text = openFileDialog1.FileName;
            box.Focus();
        }
        else {
            box.Text = "";
        }
    }

    private void button1_Click(object sender, EventArgs e) {
        openFile(textBox1);
    }
like image 149
Hans Passant Avatar answered Jul 08 '26 11:07

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!