我有两个文本框和每个文本框旁边的2个按钮。是否有可能使用一个OpenFileDialog并将FilePath传递到相应的文本框,基于哪个按钮被点击?即...如果我点击按钮并放置对话框,当我单击对话框上的打开对象时,它会将文件名传递给第一个文本框。重复使用OpenFileDialog
2
A
回答
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);
}
相关问题
- 1. c#/重命名DLL使用OpenFileDialog
- 2. 没有使用openfiledialog
- 3. 使用OpenFileDialog和StreamReader
- 4. 使用GetOpenFileName而不是OpenFileDialog
- 5. OpenFileDialog:使用复选框选择多个文件
- 6. 使用重复
- 7. 复制从OpenFileDialog选定的文件c#
- 8. Wxpython剪切复制粘贴和openfiledialog
- 9. OpenFileDialog Image
- 10. OpenFileDialog FileNames
- 11. OpenFileDialog Silverlight
- 12. OpenFileDialog Spy
- 13. Openfiledialog safefilenames
- 14. Openfiledialog Multiselect
- 15. 使用多重ng重复
- 16. 在C#中使用OpenFileDialog保存文件
- 17. 使用OpenFileDialog和Multiselect搜索字符串
- 18. 使用VBA访问已打开的OpenFileDialog
- 19. 在OpenFileDialog中使用DialogResult.OK时出错
- 20. 如何使用openFileDialog指定rootfolder
- 21. 如何在silverlight中使用openfiledialog
- 22. 使用openfiledialog移动多个文件
- 23. 如何使用OpenFileDialog选择文件夹?
- 24. 如何使控制像OpenFileDialog?
- 25. 如何使OpenFileDialog变量Global?
- 26. 重复使用跨
- 27. 重复使用HttpURLConnection
- 28. 重复使用者
- 29. 重复使用FtpWebRequest
- 30. 重复使用MFMailComposeViewController
这是可能的。也许你可以解释一下你需要帮助的问题。你想知道哪个按钮被按下? – 2010-01-13 22:01:31
添加...我尊重@FredrikMörk – 2010-01-13 22:15:19
+1以及其他答案,因为两者都可行。 – David 2010-01-13 22:37:26