代码之家  ›  专栏  ›  技术社区  ›  Saif Khan

重用OpenFileDialog

  •  2
  • Saif Khan  · 技术社区  · 15 年前

    我有两个文本框,每个文本框旁边有两个按钮[…]。是否可以使用一个OpenFileDialog并根据单击的按钮将文件路径传递到相应的文本框?i、 如果我单击Button one并打开对话框,当我单击对话框上的open时,它会将文件名传递到第一个文本框。

    4 回复  |  直到 15 年前
        1
  •  2
  •   David    15 年前

    这对我来说很有效(而且比其他帖子简单,但它们中的任何一个都可以)

    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;
    }
    
        2
  •  4
  •   Hans Passant    12 年前

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

        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);
        }
    
        3
  •  3
  •   Fredrik Mörk    15 年前

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

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

        4
  •  2
  •   Russell    15 年前

    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.
       }
    }