重用OpenFileDialog

时间:2010-01-13 21:54:41

标签: .net openfiledialog

每个文本框旁边有2个文本框和2个按钮[...]。是否可以使用一个OpenFileDialog并根据单击的按钮将FilePath传递到相应的文本框?即...如果我点击按钮然后点击对话框,当我在对话框上单击打开时,它会将fileName传递给第一个文本框。

4 个答案:

答案 0 :(得分:4)

每当你想到“有共同的功能!”你应该考虑一种实现它的方法。它看起来像这样:

    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);
    }

答案 1 :(得分:3)

有几种方法可以做到这一点。一种是使用Dictionary<Button, TextBox>来保存按钮及其相关文本框之间的链接,并在按钮的单击事件中使用该按钮(两个按钮可以连接到同一个事件处理程序):

public partial class TheForm : Form
{
    private Dictionary<Button, TextBox> _buttonToTextBox = new Dictionary<Button, TextBox>();
    public Form1()
    {
        InitializeComponent();
        _buttonToTextBox.Add(button1, textBox1);
        _buttonToTextBox.Add(button2, textBox2);
    }

    private void Button_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            _buttonToTextBox[sender as Button].Text = ofd.FileName;
        }
    }
}

当然,上面的代码应该使用空检查,良好的行为封装等等来装饰,但是你明白了。

答案 2 :(得分:2)

是的,基本上您需要保持对单击按钮的引用,然后将文本框映射到每个按钮:

public class MyClass
{
  public Button ClickedButtonState { get; set; }
  public Dictionary<Button, TextBox> ButtonMapping { get; set; }

  public MyClass
  {
    // setup textbox/button mapping.
  } 

   void button1_click(object sender, MouseEventArgs e)
   {
     ClickedButtonState = (Button)sender;
     openDialog();
   }

   void openDialog()
   {
     TextBox current = buttonMapping[ClickedButtonState];
     // Open dialog here with current button and textbox context.
   }
}

答案 3 :(得分:2)

这对我有用(而且比其他帖子更简单,但其中任何一个都可以正常工作)

private void button1_Click(object sender, EventArgs e)
{
    openFileDialog1.ShowDialog();
    textBox1.Text = openFileDialog1.FileName;
}

private void button2_Click(object sender, EventArgs e)
{
    openFileDialog1.ShowDialog();
    textBox2.Text = openFileDialog1.FileName;
}