【问题标题】:Reusing OpenFileDialog重用 OpenFileDialog
【发布时间】:2010-01-13 21:54:40
【问题描述】:

每个文本框旁边都有 2 个文本框和 2 个按钮 [...]。是否可以使用一个 OpenFileDialog 并将 FilePath 传递给相应的文本框,基于单击哪个按钮?即...如果我单击按钮一个并加载对话框,当我单击对话框上的打开时,它会将文件名传递给第一个文本框。

【问题讨论】:

  • 这是可能的。也许你可以解释这个问题中你需要帮助的部分。您是否想弄清楚按下了哪个按钮??
  • 补充...我尊重@Fredrik Mörk
  • 对其他答案也+1,因为两者都是可行的。

标签: .net openfiledialog


【解决方案1】:

只要您认为“有通用功能!”你应该考虑一种实现它的方法。它可能看起来像这样:

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

【讨论】:

    【解决方案2】:

    有几种方法可以做到这一点。一种是有一个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;
            }
        }
    }
    

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

    【讨论】:

      【解决方案3】:

      这对我有用(它比其他帖子更简单,但它们中的任何一个都可以)

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

      【讨论】:

      • 没错。 @HansPassant 的答案更好。它检查 DialogResult.OK
      【解决方案4】:

      是的,基本上你需要保留对被点击按钮的引用,然后是文本框到每个按钮的映射:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-28
        • 1970-01-01
        • 2014-03-09
        • 2016-02-17
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多