문제

각 텍스트 상자 옆에 2 개의 텍스트 상자와 2 개의 버튼 [...]이 있습니다. 하나의 OpenFileDialog를 사용하고 어떤 버튼을 클릭 한 버튼을 기반으로 FilePath를 해당 텍스트 상자에 전달할 수 있습니까? 즉, Buttton One을 클릭하고 대화 상자를 laod하면 대화 상자를 클릭하면 파일 이름을 첫 번째 텍스트 상자로 전달합니다.

도움이 되었습니까?

해결책

이것은 나를 위해 효과가 있었고 (그리고 다른 게시물보다 간단하지만 그들 중 하나도 효과가있을 것입니다).

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

다른 팁

"일반적인 기능이 있다고 생각할 때마다!" 이를 구현하는 방법을 고려해야합니다. 다음과 같이 보일 수 있습니다.

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

이를 수행하는 방법에는 여러 가지가 있습니다. 하나는 a 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;
        }
    }
}

물론 위의 코드는 널 체크, 동작의 멋진 캡슐화 등으로 장식해야하지만 아이디어를 얻습니다.

예, 기본적으로 클릭 한 버튼에 대한 참조를 유지 한 다음 각 버튼에 텍스트 상자를 매핑해야합니다.

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.
   }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top