簡體   English   中英

處理多個表單之間的數據

[英]Handling data between multiple Forms

我正在研究一個生成PDF文件的程序。 在最終生成文件之前,我想給用戶一個選項來編輯文件的一部分(即將創建的圖形的標題)。 我希望當用戶單擊按鈕以導出PDF時以新的形式顯示。 這是我要做什么的概述...

private void button4_Click(object sender, EventArgs e) // Test PDF Code!
{
    Form2 NewPDF = new Form2(chart3.Titles[chart3.Titles.IndexOf("Header")].Text.ToString().Substring(0, chart3.Titles[chart3.Titles.IndexOf("Header")].Text.ToString().Length - 4));
    NewPDF.Show(); 

    if (NewPDF.Selected == true)
    {
       // Create PDF, open save file dialog, etc             
    }
}

這是通過此按鈕單擊打開的窗體。

public partial class Form2 : Form
{

    public bool Selected
    {
        get;
        set;
    }

    public String GraphName
    {
        get;
        set;
    }


    public Form2(String FileName)
    {
        InitializeComponent();
        textBox1.Text = FileName;
        GraphName = FileName;
        Selected = false;
    }

   public void button1_Click(object sender, EventArgs e)
    {
        GraphName = textBox1.Text;
        this.Selected = true; // After the button is selected I want the code written above to continue execution, however it does not!
    }
}

到目前為止,當我單擊Form2中的按鈕時,什么都沒有發生,這是我不了解的關於兩個Forms之間通信的信息!

您問題的答案很簡單。

NewPDF.Show();

Show()不會暫停調用表單的執行。 因此,如果選擇的屬性為true,則驗證其下方的檢查將永遠不會正確執行,因為在表單開始顯示時,已達到並驗證了該檢查。 ShowDialog()會暫停執行並等待調用的窗體關閉。

那邊 我建議使用兩種其他方式在表單之間進行通信;

  1. 使用全局變量。 在公共模塊中的某個地方聲明一個保存圖形名稱的變量。 調用要求用戶使用ShowDialog()輸入名稱的對話框,因為這會暫停執行調用表單,直到被調用表單返回結果為止。

     if(Form.ShowDialog() == DialogResult.OK) { // Save pdf, using title in global variable } 

    確保在Close()-ing之前以調用的形式設置DialogResult。

  2. 將調用表單的實例變量傳遞給構造函數的被叫名稱輸入表單並保存。 這樣,如果將圖形名稱屬性公開為公共屬性,則應該能夠從關閉表單的代碼中的被調用表單訪問它,即:

      public void button1_Click(object sender, EventArgs e) { callingFormInstance.GraphNameProperty = textBox1.Text; Close(); } 

希望能有所幫助。 干杯!

您應該像下面那樣更改Form2.GraphName

public String GraphName
{
    get { return textBox1.Text }
}

然后更改您的新Form2創建,如下所示,進行測試,因為我還沒有通過VS運行它,但是應該可以正常工作:)

private void button4_Click(object sender, EventArgs e) // Test PDF Code!
{
    // why on earth were you doing .Text.ToString()?  it's already string...
    Form2 NewPDF = new Form2(chart3.Titles[chart3.Titles.IndexOf("Header")].Text.Substring(0, chart3.Titles[chart3.Titles.IndexOf("Header")].Text.Length - 4));

    // show as a dialog form, so it will wait for it to exit, and set this form as parent
    NewPDF.ShowDialog(this); 

    if (NewPDF.Selected == true)
    {
        // get the name from the other form
        string fileName = NewPDF.GraphName;

       // Create PDF, open save file dialog, etc
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM