2

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

4

4 回答 4

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);
    }
于 2010-01-13T22:09:02.293 回答
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;
        }
    }
}

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

于 2010-01-13T22:01:07.613 回答
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.
   }
}
于 2010-01-13T22:01:14.637 回答
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;
}
于 2010-01-13T22:02:49.150 回答