2017-08-04 9 views
-1

C#アプリケーションで使用したコードで問題が発生しました。ブラウズボタンをクリックしてファイルを選択すると、ダイアログボックスが2回開きます。C#プログラムでOpenFileDialogを2回開く

private void txt_location_TextChanged(object sender, EventArgs e) 
{ 
    string folderPath = ""; 
    FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog(); 
    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { 
     folderPath = folderBrowserDialog1.SelectedPath; 
    } 
} 

private void Button21_Click(object sender, EventArgs e) 
{ 
    using(var fbd = new FolderBrowserDialog()) { 
     DialogResult result = fbd.ShowDialog(); 

     if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) { 
      selectedPath = fbd.SelectedPath; 
      txt_location.Text = selectedPath; 
     } 
    } 
} 

private void bunifuThinButton21_Click_1(object sender, EventArgs e) 
{ 
    System.IO.StreamWriter file; 
    bool isvalid = ValidateInputs(); 
    try { 
     file = new System.IO.StreamWriter(selectedPath + @ "\dred.txt"); 

     catch (Exception ex) { 
      MessageBox.Show("Please, Select valid Path.."); 
      return; 
     } 
     try { 
      if (isvalid) { 
       WriteLines(file); 
      } 
     } 
     catch (Exception ex2) { 
      MessageBox.Show(ex2.Message); 
     } 
     finally { 
      file.Close(); 
     } 
    } 
} 

明らかに、選択したファイルを読み取ることができるようにするために1回だけ開くことを意味します。これは動作しますが、一度だけファイルを2回選択しました。

ご協力いただきありがとうございます。

+1

これは、 'Button21_Click'の' txt_location'の値を変更すると 'txt_location'から' TextChanged'イベントが発生し、 'txt_location_TextChanged'が呼び出されるからです。 – litelite

+0

何かを入力するか、txt_locationテキストボックスにテキストを変更するたびにFolderBrowserDialogを開くことに気づいていますか?このテキストボックスのテキストをボタンイベント内に設定すると、イベントが呼び出されます。 – Steve

答えて

0

あなたはFolderBrowserDialogをインスタンス化し、二つの異なるイベントに示されている: は、それぞれが一回、別々に発射されているため、次の2つのポップアップを抱えている

Button21_Click

をtxt_location_TextChangedと 。

もう一度FolderBrowserDialogをポップしていない別のものに必要な場合を除き、イベントtxt_location_TextChangedを完全に削除する必要があります。

関連する問題