各テキストボックスの横に 2 つのテキストボックスと 2 つのボタン [...] があります。どのボタンがクリックされたかに基づいて、1 つの OpenFileDialog を使用して FilePath をそれぞれのテキスト ボックスに渡すことは可能ですか? つまり、ボタン 1 をクリックしてダイアログをロードすると、ダイアログで [開く] をクリックすると、fileName が最初のテキスト ボックスに渡されます。
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
これを行うにはいくつかの方法があります。1 つは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 に答える