Home > Software design >  C# .Net determine which control call for OpenFileDialog
C# .Net determine which control call for OpenFileDialog

Time:09-16

I have a single OpenFileDialog and there are three textboxes that are showing it on click. I want to know which textboxes call it.

private void tb_one_Click(object sender, EventArgs e) {
        openFileDialog.ShowDialog();
}

private void tb_two_Click(object sender, EventArgs e) {
        openFileDialog.ShowDialog();
}

private void tb_three_Click(object sender, EventArgs e) {
        openFileDialog.ShowDialog();
}


private void openFileDialog_FileOk(object sender, CancelEventArgs e) {
   //determine which textbox call this.
     Console.WriteLine((Control)sender); //this one is failed, throws cast exception error.
     Console.WriteLine((TextBox)sender); //this one is failed, throws cast exception error.
     Console.WriteLine(sender);          //this shows only the information of selected file in console.
   //get the path and file of selected file.
   //put the path into corresponding textbox.
}

is that possible?

CodePudding user response:

Instead of the OpenFileDialog event, you need to do that in the TextBox click event.

    private void tb_one_Click(object sender, EventArgs e) {
        if (openFileDialog.ShowDialog() == DialogResult.OK) {
            TextBox textBox = (TextBox)sender;
            textBox.Text = openFileDialog.FileName; //put the path into this textBox
        }
    }

    private void tb_two_Click(object sender, EventArgs e) {
        if (openFileDialog.ShowDialog() == DialogResult.OK) {
            TextBox textBox = (TextBox)sender;
            textBox.Text = openFileDialog.FileName; //put the path into this textBox
        }
    }

    private void tb_three_Click(object sender, EventArgs e) {
        if (openFileDialog.ShowDialog() == DialogResult.OK) {
            TextBox textBox = (TextBox)sender;
            textBox.Text = openFileDialog.FileName; //put the path into this textBox
        }
    }
    

    

    
  • Related