2010-01-13 34 views
2

我有两个文本框和每个文本框旁边的2个按钮。是否有可能使用一个OpenFileDialog并将FilePath传递到相应的文本框,基于哪个按钮被点击?即...如果我点击按钮并放置对话框,当我单击对话框上的打开对象时,它会将文件名传递给第一个文本框。重复使用OpenFileDialog

+0

这是可能的。也许你可以解释一下你需要帮助的问题。你想知道哪个按钮被按下? – 2010-01-13 22:01:31

+0

添加...我尊重@FredrikMörk – 2010-01-13 22:15:19

+0

+1以及其他答案,因为两者都可行。 – David 2010-01-13 22:37:26

回答

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

如果用户点击“取消”,这将无法正常工作。 – 2012-11-06 12:40:16

+0

这是正确的。 @ HansPassant的回答比较好。它检查DialogResult.OK – David 2012-11-06 13:30:42

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

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

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